我有一个php类(ajax调用),它返回json_encode
数据
["2016-02-08 09:00:00.000","2016-02-15 09:00:00.000"]
我正在尝试做jquery.parseJSON(data)
,它给了我错误"Unexpected number"
,我做错了什么?
您正在尝试解析数组,而不是字符串。 JSON.parse
(和任何其他 JSON 解析器)需要一个字符串,因此调用Array.toString
并且您的调用变得jquery.parseJSON("2016-02-08 09:00:00.000,2016-02-15 09:00:00.000")
//Error "Unexpected number", toString is called on the input array
JSON.parse(["2016-02-08 09:00:00.000","2016-02-15 09:00:00.000"])
// Returns an array object
JSON.parse('["2016-02-08 09:00:00.000","2016-02-15 09:00:00.000"]') // OK
如果你使用的是内联json_encode
的返回,你不需要解析它,只需将其分配给一个变量,JavaScript 就会做解析。
var dates = <?= json_encode($dates) ?>;
如果您使用的是jQuery
则数据通常已经在回调中解析为 JSON,如果没有,您可以使用 dataType: 'json'
强制使用
var x = '["2016-02-08 09:00:00.000","2016-02-15 09:00:00.000"]';
$.parseJSON(x) // return an array
当你使用 JSON 数据类型执行 AJAX 调用时,jQuery 会为你进行解码:
$.ajax({
url: 'mypage.php',
data: mydata,
dataType: 'json'
})
.done(function(response) {
// Response is an array, not a JSON string, jQuery decoded it.
// Demo:
console.log(response[0]); // "2016-02-08 09:00:00.000"
console.log(response[1]); // "2016-02-15 09:00:00.000"
}
这在jQuery文档中进行了解释:
数据类型
...
"json"
:以 JSON 形式评估响应并返回 JavaScript 对象。
因此,不要对结果使用jquery.parseJSON
。它已经为您完成了。