3

我正在尝试用 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}
4

4 回答 4

15

alert(data[currCounter]),这将起作用。

asdata.currCounter在对象中查找键“currCounter”,而不是通过 currCounter 的值。

例子:

http://jsfiddle.net/bJeWm/1/

var myObj = { 'name':'dhruv','age':28 };
var theKey = 'age';
alert(myObj.theKey);  // undefined
alert(myObj[theKey]); // 28
于 2013-06-04T07:00:22.847 回答
3

利用

alert(data[currCounter]); 

反而。您不能像以前那样访问属性......

于 2013-06-04T07:01:21.197 回答
2

需要使用[]符号

data[currCounter]
于 2013-06-04T07:01:57.913 回答
1

尝试 data[currCounter],因为 data.currCount 中没有值。

于 2013-06-04T07:02:28.090 回答