【发布时间】:2011-04-22 19:20:39
【问题描述】:
我正在尝试获取一个字典对象,该对象在服务器端转换为 json 对象(以及正确的内容类型标头),但由于某种原因,即使我可以访问部分数据,其他部分也不能'不显示,并且 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是对的,但是我的代码不会检测到并使用它。
当我直接进入我的 json 数据打印在屏幕上的 ashx 页面时,我得到了这个 json 对象:
{"id":1,"json":[5,10,15,20],"0":"99"}
只是一个示例 json 输出。那么json.length怎么不是3???
更新:所以我将我的 asp.net 代码从 Dictionary 更改为 List,然后添加了相同的值。突然间,长度开始起作用了。 ?!?!?!那么对象在javascript中没有长度吗?
【问题讨论】:
-
你确定没有跨域问题?
-
不,我在 localhost 上测试这个并且服务器在 localhost IIS7 上运行。使用的 url 是“../check.ashx”(我也可以看到服务器返回 '99',所以显然它正在工作。)
-
if (!json.length) 如果 json.length = 0、未定义或空白,则为真。你想提醒 json[0] 和 json.length?如果长度未定义,这将失败
-
看,json.length 不应该为 0、未定义或空白,因为显然 json 有数据。所以在我上面的代码中, json[0] 有数据......但是 json.length 是未定义的。不可能。显然出了什么问题。如果 json[0] 有数据,则 json.length 应至少为 1。此代码已在其他示例代码中以这种方式使用,因此它不应该为 !json.length 返回 true。
标签: javascript ajax json jquery