jQuery JSON 值在 javascript 中被解析为未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16911570/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:02:10  来源:igfitidea点击:

JSON values parsed as undefined in javascript

javascriptjsonjquery

提问by Riju Mahna

I am trying to parse a JSON in Javascript. The JSON is created as an ajax response:

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

But all values alert 'undefined' as value (except the 'counter' which gives correct value) The actual string as seen in firebug is as below:

但是所有值都警告“未定义”作为值(除了给出正确值的“计数器”)在萤火虫中看到的实际字符串如下:

{"testPath1":"ab/csd/sasa", "testPath2":"asa/fdfd/ghfgfg", "testPath3":"ssdsd/sdsd/sds", "counter":3}

回答by DhruvPathak

alert(data[currCounter]), this will work.

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

as data.currCounterlooks for the key 'currCounter` in the object, not by the value of currCounter.

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

example:

例子:

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

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

var myObj = { 'name':'dhruv','age':28 };
var theKey = 'age';
alert(myObj.theKey);  // undefined
alert(myObj[theKey]); // 28

回答by sjkm

Use

alert(data[currCounter]); 

instead. You cannot access a property like you did....

反而。您无法像以前那样访问属性....

回答by Sushanth --

Need to use []notation

需要使用[]符号

data[currCounter]

回答by user2059250

Try data[currCounter] because there is no value in data.currCount.

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