gpt4 book ai didi

javascript - JSON.parse(xmlhttp.responseText) 返回未定义

转载 作者:行者123 更新时间:2023-12-03 04:04:02 25 4
gpt4 key购买 nike

我对 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);
}
}

最佳答案

当您在评论中发布时,这是您的回复文本:

{  
"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

关于javascript - JSON.parse(xmlhttp.responseText) 返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44637658/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com