我试图获取一个在服务器端转换为 json 对象的字典对象(以及正确的内容类型标头),但由于某种原因,即使我可以访问部分数据,其他部分也不会显示up 和 jquery 中的 json 对象的长度等于 0。
这是我的 jquery 调用:
$.ajax({
type : "POST",
url : cl._url,
//data : 'text='+text,
data: "{}",
contentType: "application/json; charset=utf-8",
dataType : "json",
error : function(XHR, status, error) {
alert("There was an error processing the request.\n\n"+XHR.responseText);
},
success : function(json){
if (!json.length) {
alert('There are no incorrectly spelled words...'+json[0]+ ' ' + json.length);
} else {
// highlight bad words
}
cl.$container.html(html);
// execute callback function, if any
(callback != undefined) && callback();
}
});
我通常会收到包含此代码的警报框,并且 json[0] 按预期打印出 99。但 json.length 是“未定义”。所以从某种意义上说,返回的 json 是正确的,但我的代码不会检测到它并使用它。
当我直接进入 ashx 页面(其中 json 数据打印在屏幕上)时,我得到以下 json 对象:
{"id":1,"json":[5,10,15,20],"0":"99"}
只是一个示例 json 输出。那么为什么 json.length 不是 3???
更新:所以我更改了我的 asp.net 代码,从字典更改为列表,然后添加相同的值。突然之间,长度开始发挥作用了。 ?!?!?!那么 JavaScript 中的对象没有长度吗?