JSON.parse(xmlhttp.responseText)返回undefined

时间:2017-06-19 18:37:49

标签: javascript

我对javascript很新,所以这可能是一个简单的问题。当我调用下面的函数时,我无法将JSON.parse(xmlhttp.responseText)分配给" obj"在这个功能。

但是,我可以将字符串xmlhttp.responseText分配给变量,然后在加载函数后在控制台中将JSON.Parse分配给它?

任何想法为什么?

function GetFacilities(e) {
         try {

      var xmlhttp;
      if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
      } else if (window.ActiveXObject) {
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
      }

      xmlhttp.open("POST", "Widgets/Example/LocationWidget/Service.asmx/GetFacilities", true);
      xmlhttp.setRequestHeader("content-type", "application/json");
      xmlhttp.setRequestHeader("Accept", "application/json");
      xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4) {
            if (xmlhttp.status == 200) {

                var obj = JSON.parse(xmlhttp.responseText);

                alert(obj.length);


          }
        }
      };
      xmlhttp.send(null);


    } catch(ex) {
      alert(ex.message);
    }
  }

1 个答案:

答案 0 :(得分:1)

正如您在评论中发表的那样,这是您的回复文字:

{  
   "d":[  
      {  
         "__type":"Example.LocationWidget.Service+Facility",
         "‌​a":"ol",
         "conc":5.000         ‌​0
      },
      {  
         "__type":"Exampl‌​e.LocationWidget.Ser‌​vice+Facility",
         "a":"‌​bi",
         "conc":0.600000
      }      ‌​,
      {  
         "__type":"Example.‌​LocationWidget.Servi‌​ce+Facility",
         "a":"tr‌​",
         "conc":6.0000
      },
      {  
         "_‌​_type":"Example.Loca‌​tionWidget.Service+F‌​acility",
         "a":"benz",
         ‌​"c":1.000
      }
   ]
}

因此,如果您调用obj.length未定义,因为json对象不是数组。您应该拨打obj.d.length