解析json时出现数字错误

时间:2016-02-09 21:55:20

标签: php jquery json ajax

我有一个php类(调用ajax),它将json_encode数据作为

返回
["2016-02-08 09:00:00.000","2016-02-15 09:00:00.000"]

我试图jquery.parseJSON(data)并且它给了我错误"Unexpected number",我做错了什么?

3 个答案:

答案 0 :(得分:2)

您正在尝试解析数组,而不是字符串。 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'强制它

答案 1 :(得分:0)

var x = '["2016-02-08 09:00:00.000","2016-02-15 09:00:00.000"]';
$.parseJSON(x) // return an array

答案 2 :(得分:0)

当您使用JSON dataType执行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 docs

中对此进行了解释
  

<强>的dataType

     

...
  "json":将响应计算为JSON并返回JavaScript对象。

所以,不要在结果上使用jquery.parseJSON。它已经为你完成了。