使用 JSON 返回对 PHP 脚本的 jQuery AJAX 调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19155192/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 18:56:05  来源:igfitidea点击:

jQuery AJAX Call to PHP Script with JSON Return

javascriptphpjqueryajaxjson

提问by Steven Marks

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 显示未定义而不是值:

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.statusand data['status']: still no joy though.

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

Any help would be really appreciated.

任何帮助将非常感激。

回答by Sorter

Make it dataTypeinstead 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. Check Content-Typeof the response header to verify, if the response is json. It should be application/jsonfor dataType:'json'and text/htmlfor dataType:'html'.

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

回答by Shakti Patel

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

回答by mujaffars

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

回答by Pankaj Sharma

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

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

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

回答by Arleal

Your datatype is wrong, change datatype for dataType.

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