我对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);
}
}
答案 0 :(得分:1)
正如您在评论中发表的那样,这是您的回复文字:
{
"d":[
{
"__type":"Example.LocationWidget.Service+Facility",
"a":"ol",
"conc":5.000 0
},
{
"__type":"Example.LocationWidget.Service+Facility",
"a":"bi",
"conc":0.600000
} ,
{
"__type":"Example.LocationWidget.Service+Facility",
"a":"tr",
"conc":6.0000
},
{
"__type":"Example.LocationWidget.Service+Facility",
"a":"benz",
"c":1.000
}
]
}
因此,如果您调用obj.length
未定义,因为json对象不是数组。您应该拨打obj.d.length
。