【问题标题】:JSON values parsed as undefined in javascript [duplicate]JSON值在javascript中解析为未定义[重复]
【发布时间】: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


【解决方案1】:

使用

alert(data[currCounter]); 

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      需要使用[]表示法

      data[currCounter]
      

      【讨论】:

        【解决方案4】:

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

        data.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
        

        【讨论】:

        • 谢谢@DhruvPathak .. 它只是通过使用 [] 而不是 "." 来工作
        猜你喜欢
        • 1970-01-01
        • 2020-08-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-10
        • 2017-01-09
        • 1970-01-01
        • 2019-05-24
        相关资源
        最近更新 更多