我正在从服务器端代码中检索值,这是我的值..
["INCOMING",09:09:49,"INETCALL",00:14:09,"ISD",00:05:50,"LOCAL",02:38:02,"STD",01:39:28]
现在根据我的需要,我想将其解析为JSON,但在解析它时会出错...
SyntaxError: JSON.parse: expected ',' or ']' after array element
var dbdata=JSON.parse(data);
这是我从服务器端获取值并将其解析为json的代码..
$.ajax({
type: 'GET',
url: 'getdataduration',
async:false,
dataType: "text",
success: function(data) {
var dbdata=JSON.parse(data);
for(var i=0,len=dbdata.length;i<len;i++){
$.isNumeric(dbdata[i]) ? callduration.push(dbdata[i]) : toc.push(dbdata[i]);
}
}
});
请伙计们帮助我。 提前谢谢..
答案 0 :(得分:2)
服务器的值不是JSON fromat,它是数组! JSON格式参考:https://developer.mozilla.org/en-US/docs/JSON
我认为您应该从服务器生成数据,如下所示:
[{"INCOMING":"09:09:49","INETCALL":"00:14:09","ISD":"00:05:50","LOCAL":"02:38:02","STD":"01:39:28"}]
答案 1 :(得分:1)
该值无效JSON也无效JS。每隔一个元素无效
E.g 09:09:49
无效(可能)"09:09:49"
以下是有效数组,可以使用JSON.parse
进行解析["INCOMING","09:09:49","INETCALL","00:14:09","ISD","00:05:50","LOCAL","02:38:02","STD","01:39:28"]
测试这类问题的一种简单方法是将服务器回复转储到浏览器开发控制台中,看看有什么错误产生
答案 2 :(得分:0)
将您的数据更改为格式
["INCOMING","09:09:49","INETCALL","00:14:09","ISD","00:05:50","LOCAL","02:38:02","STD","01:39:28"]
答案 3 :(得分:0)
您可以使用此Web工具轻松测试JSON的有效性:
Parse error on line 2:
... "INCOMING", 09: 09: 49, "INE
----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['
正如bipen所说,如果您使用PHP,请使用json_encode()发送您的数据;并将json作为数据类型放在$ .ajax
中答案 4 :(得分:0)
更正JSON数据:
// you should create your json like this
var data = '[{
"INCOMING" : "09: 09: 49",
"INETCALL" : "00: 14: 09",
"ISD" : "00: 05: 50",
"LOCAL" : "02: 38: 02",
"STD" : "01: 39: 28"
}
]';
使用JSON正确使用Ajax:
// use 'type: post' and 'dataType: json'. Because, post is safe and
you are dealing with json data so it must be dataType: json
$.ajax({
type : 'POST',
url : 'getdataduration',
async : false,
dataType : "JSON",
success : function (data) {
var dbdata = JSON.parse(data);
for (var i = 0, len = dbdata.length; i < len; i++) {
$.isNumeric(dbdata[i].YOUR_JSON_KEY)
? callduration.push(dbdata[i].YOUR_JSON_KEY)
: toc.push(dbdata[i].YOUR_JSON_KEY);
}
}
});
<强>结论:强>
You are using '$.isNumeric(dbdata[i])' but, as your json data your
first value is string. So it's not gonna to work.