这是代码:(#debug div文本如下所示)
$("#debug").text(JSON.stringify(data));
// Try to save to a file
$.ajax({
type: 'POST',
url: './json.php',
dataType: 'json',
data: JSON.stringify(data),
success: function(xhr, status, errorMessage) {
if( xhr.responseText == "Success" ) {
alert("Success!");
} else {
alert("response was "+xhr.responseText);
}
},
error: function(xhr, status, errorMessage) {
$("#debug").append("RESPONSE: "+xhr.responseText+", error: "+errorMessage);
}
});
JSON.php页面是:
<?php
openlog("scriptLog.txt", LOG_PID | LOG_PERROR, LOG_LOCAL0);
$json = $_POST['json'];
// open syslog, include the process ID and also send
// the log to standard error, and use a user defined
// logging mechanism
syslog(LOG_DEBUG, "Received Data");
if (json_decode($json) != null) { /* sanity check */
$file = fopen('./data.json','w+');
fwrite($file, json_decode($json));
fclose($file);
} else {
syslog(LOG_DEBUG,"Failure");
return "Failure, json decode is null";
}
closelog();
return "Success";
?>
在日志中我得到了以下信息:
3月14日14:50:54 scriptLog.txt[21902] : 收到数据
3月14日14:50:54 scriptLog.txt[21902] : 失败
在调试div文本中我得到了以下内容:
{"1457981454959":{"id":1457981454959,"code":"1","title":"Test","date":"22/03/2016","description":"a Task"}}RESPONSE: , error: SyntaxError: JSON Parse error: Unexpected EOF
1) 我该如何检查已发布数据的结构?例如,如何在系统日志中使用“接收到的数据:”+WHAT来查看其结构。 2) JSON解析错误?我看到的大多数示例都使用stringify函数,然后使用json_decode来获取值。为什么会出现解析错误?
_POST['json']
的东西,你只是发送了一个没有键的字符串,而且似乎发送的 JSON 中甚至没有这个名称的键?此外,解析错误是因为你使用了dataType:json
,它期望从服务器获取 JSON,但实际上它只是得到了一个普通的字符串,比如Success
等。 - adeneodata:data
,jQuery将把它转换为x-www-form
,以便您可以通过键“_POST”使用它,并确保从服务器返回有效的JSON。 - adeneo