【问题标题】:JSON parse error response "status":200,"statusText":"OK"JSON 解析错误响应 "status":200,"statusText":"OK"
【发布时间】:2016-07-08 07:03:23
【问题描述】:

我正在尝试发送 JSON 对象,但结果它发送了一个解析错误。

{"readyState":4,"responseText":"","status":200,"statusText":"OK"}

这里是代码

var data = {
  fb_id: response.id,
  email: response.email,
  name: response.name,
  first_name: response.first_name,
  last_name: response.last_name,
  verified: response.verified,
  birthday:response.birthday,
  picture: response.picture.data.url,
  hometown: response.hometown.name,
  gender: response.gender 
};
$.ajax({
  url:'connect.php',
  type: 'POST',
  data: {
    user: data
  },
  dataType: 'JSON',
  success: function(html){
    //page();
    console.log(JSON.stringify(data));
  },
  error: function(XMLHttpRequest, textStatus, errorThrown) {
    if (XMLHttpRequest.readyState == 4) {
      console.log(JSON.stringify(XMLHttpRequest));
    }
  }

});

后端在这里: JSON 对象在这里发送

if(isset($_POST['user'])) {
  //convert json object to php associative array
  $data = $_POST['user'];
  $fbid = $data['fb_id'];             // To Get Facebook ID
  $fbfullname = $data['name']; // To Get Facebook full name
  $femail = $data['email'];    // To Get Facebook email ID
  $fbname = $data['first_name'];
  $fblname = $data['last_name'];
  $fbgender = $data['gender'];
  $fverified = $data['verified'];
  $faddress = $data['hometown'];
  $fbirth = $data['birthday'];
  $img = $data['picture'];

}

对象正在发送类似的东西:

{
    "fb_id":"xxxxxxxxxxx99",

    "email":"sxxxxxx@xxx.in",

    "name":"Sagar xxxx",
    ...
}

PS:我使用的是1.12.4版本的jquery.min.js

更新 当我尝试使用此查询向 connect.php 页面发送请求时,它会在控制台日志中返回错误。如果我将 dataType 更改为“text”或将其排除,则它不会返回任何错误,但 connect.php 无法识别使用 ajax 请求发布的任何查询,即 isset($_POST['user']) 将无法识别任何查询。

【问题讨论】:

  • 再写一些,到底是php还是js哪边出错了?

标签: json ajax parsing


【解决方案1】:

在您的 php 脚本中,在读取 json 后添加此代码:

  if(isset($_POST['user']))
  {
 //convert json object to php associative array
  $data = $_POST['user'];
  $fbid = $data['fb_id'];            // To Get Facebook ID
  $fbfullname = $data['name']; // To Get Facebook full name
  $femail = $data['email'];    // To Get Facebook email ID
  $fbname = $data['first_name'];
  $fblname = $data['last_name'];
  $fbgender = $data['gender'];
  $fverified = $data['verified'];
  $faddress = $data['hometown'];
  $fbirth = $data['birthday'];
  $img = $data['picture']; 

添加此代码:

  header("Content-Type: application/json", true); 

  /* Return JSON */
  echo json_encode("Success");

  /* Stop Execution */
  exit; 

}

“成功”文本发送至onSuccess(html)

【讨论】:

    【解决方案2】:

    我不是 PHP 专家,但问题可能是您将 JSON 作为帖子正文发送,而在后端以 urlencoded 形式对其进行操作。 我想您需要从请求中获取一个普通的 json,将其解析为一个数组,然后进行处理。你可以在这里找到有用的例子Issue reading HTTP request body from a JSON POST in PHP

    还将dataType更改为“application/json”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-27
      • 2018-12-24
      • 1970-01-01
      • 2014-12-04
      相关资源
      最近更新 更多