【问题标题】:jQuery AJAX Call to PHP Script with JSON ReturnjQuery AJAX 调用带有 JSON 返回的 PHP 脚本
【发布时间】:2013-10-09 21:58:07
【问题描述】:

我一直用这个把头撞在砖墙上,我在 stackoverflow 上尝试了很多解决方案,但找不到一个有效的解决方案!

基本上,当我发布我的 AJAX 时,PHP 返回 JSON,但 AJAX 显示未定义而不是值:

JS

  /* attach a submit handler to the form */
  $("#group").submit(function(event) {

  /* stop form from submitting normally */
  event.preventDefault();

  /*clear result div*/
  $("#result").html('');

  /* get some values from elements on the page: */
  var val = $(this).serialize();

  /* Send the data using post and put the results in a div */
  $.ajax({
      url: "inc/group.ajax.php",
      type: "post",
      data: val,
  datatype: 'json',
      success: function(data){
            $('#result').html(data.status +':' + data.message);   
            $("#result").addClass('msg_notice');
            $("#result").fadeIn(1500);           
      },
      error:function(){
          $("#result").html('There was an error updating the settings');
          $("#result").addClass('msg_error');
          $("#result").fadeIn(1500);
      }   
    }); 
});

PHP

  $db = new DbConnector();
  $db->connect();
  $sql='SELECT grp.group_id, group_name, group_enabled, COUNT('.USER_TBL.'.id) AS users, grp.created, grp.updated '
        .'FROM '.GROUP_TBL.' grp '
        .'LEFT JOIN members USING(group_id) '
        .'WHERE grp.group_id ='.$group_id.' GROUP BY grp.group_id';

    $result = $db->query($sql);     
    $row = mysql_fetch_array($result);
    $users = $row['users'];
    if(!$users == '0'){
        $return["json"] = json_encode($return);
        echo json_encode(array('status' => 'error','message'=> 'There are users in this group'));
    }else{

        $sql2= 'DELETE FROM '.GROUP_TBL.' WHERE group_id='.$group_id.'';
        $result = $db->query($sql2);

        if(!$result){
            echo json_encode(array('status' => 'error','message'=> 'The group has not been removed'));
        }else{
            echo json_encode(array('status' => 'success','message'=> 'The group has been removed'));
        }
    }

来自 firebug 的 JSON 结果

{"status":"success","message":"success message"}

AJAX 将 JSON 结果显示为未定义,我不知道为什么。我尝试显示添加dataType='json'datatype='json'。我也尝试将其更改为data.statusdata['status']:但仍然没有乐趣。

任何帮助将不胜感激。

【问题讨论】:

  • 设置一个“application/json”标头header('Content-Type: application/json');
  • datatype 应该大写 T: dataType: 'json'。理论上它应该从响应中推断出类型,所以这可能无法解决问题。
  • @hank 或@Rory 的建议应该足够了。如果设置了正确的 mimetype,则无需指定 dataType

标签: javascript php jquery ajax json


【解决方案1】:

改成dataType,而不是datatype

并在 php 中添加以下代码,因为您的 ajax 请求需要 json 并且不会接受任何内容,但 json。

header('Content-Type: application/json');

Correct Content type for JSON and JSONP

firebug 中可见的响应是文本数据。检查响应头的Content-Type 以验证响应是否为json。 dataType:'json' 应该是 application/jsondataType:'html' 应该是 text/html

【讨论】:

  • 您好,谢谢!大多数帖子都说 header('Content-Type: application/json');不是必需的!显然是!
  • 如果这对您有所帮助,我很高兴。我知道当这样的事情不起作用时的感觉。是的,我过去也为此撞过墙:D,但使用了不同的服务器端语言。
  • 我确实有一个脚本仍然无法正常工作,我正在从表中删除一行,然后返回 json,但是 json 似乎前面有已删除行的 ID:@ 987654330@
  • 您必须打印并查看 php 发送的内容并进行相应的修复。
  • 这是我的问题的解决方案
【解决方案2】:

您的数据类型错误,请更改 dataType 的数据类型。

【讨论】:

    【解决方案3】:

    使用 parseJSON jquery 方法将字符串转换为对象

    var objData = jQuery.parseJSON(data);
    

    现在你可以写代码了

    $('#result').html(objData .status +':' + objData .message);
    

    【讨论】:

      【解决方案4】:

      我建议你使用:

      var returnedData = JSON.parse(data);
      

      将 JSON 字符串(如果只是文本)转换为 JavaScript 对象。

      【讨论】:

      • 如果您使用成功回调,您已经将生成的字符串解析为 javascript 对象并作为参数放入成功回调函数中。
      【解决方案5】:

      尝试从服务器发送内容类型标头在回显之前使用它

      header('Content-Type: application/json');
      

      【讨论】:

        猜你喜欢
        • 2014-01-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-18
        • 1970-01-01
        • 2011-08-11
        • 2012-03-30
        • 1970-01-01
        相关资源
        最近更新 更多