jQuery AJAX调用PHP脚本,返回JSON

时间:2022-01-12 01:22:50

I've been smashing my head against a brick wall with this one, i've tried loads of the solutions on * but can't find one that works!

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

Basically when I POST my AJAX the PHP returns JSON but the AJAX shows Undefined instead of the value:

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

JS:

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:

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'));
        }
    }

JSON Result from firebug:

firebug的JSON结果:

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

AJAX Displays the JSON result as Undefined and I dont have a clue why. I have tried displaying adding dataType='json' and datatype='json'. I have also tried changing it to data.status and data['status']: still no joy though.

AJAX将JSON结果显示为未定义的,我不知道为什么。我尝试过显示添加数据类型='json'和数据类型='json'。我也尝试过把它改成data。状态和数据['状态']:仍然没有快乐。

Any help would be really appreciated.

如有任何帮助,我们将不胜感激。

5 个解决方案

#1


40  

Make it dataType instead of datatype.

使它成为数据类型而不是数据类型。

And add below code in php as your ajax request is expecting json and will not accept anything, but json.

并且在php中添加下面的代码,因为您的ajax请求期望的是json,它不接受任何东西,只接受json。

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

Correct Content type for JSON and JSONP

纠正JSON和JSONP的内容类型

The response visible in firebug is text data. Check Content-Type of the response header to verify, if the response is json. It should be application/json for dataType:'json' and text/html for dataType:'html'.

firebug中可见的响应是文本数据。如果响应是json,请检查响应头的内容类型以进行验证。数据类型应该是application/json:'json',数据类型应该是text/html:'html'。

#2


3  

I recommend you use:

我推荐你使用:

var returnedData = JSON.parse(data);

to convert the JSON string (if it is just text) to a JavaScript object.

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

#3


2  

try to send content type header from server use this just before echoing

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

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

#4


2  

Use parseJSON jquery method to covert string into object

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

var objData = jQuery.parseJSON(data);

Now you can write code

现在您可以编写代码了

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

#5


1  

Your datatype is wrong, change datatype for dataType.

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

#1


40  

Make it dataType instead of datatype.

使它成为数据类型而不是数据类型。

And add below code in php as your ajax request is expecting json and will not accept anything, but json.

并且在php中添加下面的代码,因为您的ajax请求期望的是json,它不接受任何东西,只接受json。

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

Correct Content type for JSON and JSONP

纠正JSON和JSONP的内容类型

The response visible in firebug is text data. Check Content-Type of the response header to verify, if the response is json. It should be application/json for dataType:'json' and text/html for dataType:'html'.

firebug中可见的响应是文本数据。如果响应是json,请检查响应头的内容类型以进行验证。数据类型应该是application/json:'json',数据类型应该是text/html:'html'。

#2


3  

I recommend you use:

我推荐你使用:

var returnedData = JSON.parse(data);

to convert the JSON string (if it is just text) to a JavaScript object.

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

#3


2  

try to send content type header from server use this just before echoing

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

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

#4


2  

Use parseJSON jquery method to covert string into object

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

var objData = jQuery.parseJSON(data);

Now you can write code

现在您可以编写代码了

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

#5


1  

Your datatype is wrong, change datatype for dataType.

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