小编典典

jQuery AJAX使用JSON Return调用PHP脚本

ajax

我一直在用这个把头砸在砖墙上,我已经在stackoverflow上尝试了很多解决方案,但找不到一个可行的方案!

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

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结果显示为Undefined,我不知道为什么。我尝试显示添加dataType='json'datatype='json'。我也曾尝试将其更改为data.statusanddata['status']:尽管仍然没有乐趣。

任何帮助将非常感激。


阅读 263

收藏
2020-07-26

共1个答案

小编典典

dataType代替它datatype

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

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

在萤火虫中可见的响应是文本数据。检查Content-Type响应标头以验证响应是否为json。它应该是application/jsondataType:'json'text/htmldataType:'html'

2020-07-26