我正在尝试发送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:我使用的是jquery.min.js的1.12.4版本
更新 当我尝试使用此查询向connect.php页面发送请求时,它在控制台日志中返回错误。如果我将dataType更改为" text"或者排除它然后它不会返回任何错误但是connect.php无法识别使用ajax请求发布的任何查询,即isset($ _ POST [' user'])将无法识别任何疑问。
答案 0 :(得分:0)
我不是PHP专家,但问题可能是您将JSON作为帖子正文发送,而后端则以urlencoded格式运行。 我想你需要从请求中获取一个普通的json,将其解析为一个数组,然后进行处理。您可以在Issue reading HTTP request body from a JSON POST in PHP
找到有用的示例同时将dataType更改为“application / json”
答案 1 :(得分:0)
在你的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)