Rij*_*hna 2 javascript jquery json
我试图在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);
}
});
Run Code Online (Sandbox Code Playgroud)
但是所有值都警告'undefined'作为值(除了'counter',它给出了正确的值)在firebug中看到的实际字符串如下:
{"testPath1":"ab/csd/sasa", "testPath2":"asa/fdfd/ghfgfg", "testPath3":"ssdsd/sdsd/sds", "counter":3}
Run Code Online (Sandbox Code Playgroud)
Dhr*_*hak 14
alert(data[currCounter]) ,这会奏效.
为data.currCounter查找关键"currCounter`的对象,而不是通过currCounter的价值.
例:
var myObj = { 'name':'dhruv','age':28 };
var theKey = 'age';
alert(myObj.theKey); // undefined
alert(myObj[theKey]); // 28
Run Code Online (Sandbox Code Playgroud)