【发布时间】:2013-05-30 11:30:15
【问题描述】:
我正在尝试用 Javascript 解析 JSON。 JSON 被创建为 ajax 响应:
$.ajax(url, {
dataType: "text",
success: function(rawData, status, xhr) {
var data;
try {
data = $.parseJSON(rawData);
var counter = data.counter;
for(var i=1; i<=counter; i++){
//since the number of 'testPath' elements in the JSON depend on the 'counter' variable, I am parsing it in this way
//counter has the correct integer value and loops runs fine
var currCounter = 'testPath'+i ;
alert(data.currCounter); // everything alerts as undefined
}
} catch(err) {
alert(err);
}
},
error: function(xhr, status, err) {
alert(err);
}
});
但所有值都将“未定义”作为值警报(除了给出正确值的“计数器”)在萤火虫中看到的实际字符串如下:
{"testPath1":"ab/csd/sasa", "testPath2":"asa/fdfd/ghfgfg", "testPath3":"ssdsd/sdsd/sds", "counter":3}
【问题讨论】:
-
为什么不使用
dataType作为JSON并以JSON而不是text发送响应?? -
您检查过您的 Javascript 控制台是否有错误?
标签: javascript json jquery