简体   繁体   English

jQuery AJAX使用JSON Return调用PHP脚本

[英]jQuery AJAX Call to PHP Script with JSON Return

I've been smashing my head against a brick wall with this one, i've tried loads of the solutions on stackoverflow but can't find one that works! 我一直在用一块砖墙砸我的头,我已经在stackoverflow上尝试了大量的解决方案,但找不到一个有效的方法!

Basically when I POST my AJAX the PHP returns JSON but the AJAX shows Undefined instead of the value: 基本上当我发布我的AJAX时,PHP返回JSON,但AJAX显示Undefined而不是值:

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. AJAX将JSON结果显示为Undefined,我不知道为什么。 I have tried displaying adding dataType='json' and datatype='json' . 我试过显示添加dataType='json'datatype='json' I have also tried changing it to data.status and data['status'] : still no joy though. 我也尝试将其更改为data.statusdata['status'] :尽管如此仍然没有乐趣。

Any help would be really appreciated. 任何帮助将非常感激。

Make it dataType instead of datatype . 使其成为dataType而不是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. 在firebug中可见的响应是文本数据。 Check Content-Type of the response header to verify, if the response is json. 如果响应是json,请检查响应头的Content-Type以验证。 It should be application/json for dataType:'json' and text/html for dataType:'html' . 它应该是application/json for dataType:'json'text/html for dataType:'html'

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对象。

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

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM