jQuery的AJAX JSON响应的长度是不确定的和不正确的数据 [英] jQuery ajax json response has length undefined and incorrect data

查看:164
本文介绍了jQuery的AJAX JSON响应的长度是不确定的和不正确的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图抓住它转换成JSON对象在服务器端的一个字典对象,(以及正确的Content-Type头),但由于某些原因,即使我可以访问数据,其他部位不要的部分'T显示出来,并在jQuery的JSON对象为0长度相等。

I'm trying to grab a dictionary object which is converted to json object in server side, (along with correct content-type header), but for some reason, even though I can access part of the data, other parts don't show up and json object in jquery has length equal to 0.

下面是我的jQuery电话:

Here is my jquery call:

$.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(); 
        }
    });

我通常会用这个code警告框,和JSON [0]打印出99预期。但json.length是不确定。因此,从某种意义上说,返回的JSON是正确的,但我的code不会检测到它并使用它。

I usually get the alert box with this code, and json[0] prints out 99 as expected. But json.length is "undefined". So in a sense, the json returned is right but my code will not detect it and use it.

当我直接去哪里我JSON数据显示在屏幕上的我的ashx页面上,我得到这个JSON对象:

When I go directly to my ashx page where my json data is printed on the screen, I get this json object:

{"id":1,"json":[5,10,15,20],"0":"99"}

只是一个样本JSON输出。那么怎么来json.length不是3 ???

Just a sample json output. So how come json.length is not 3???

更新:所以我改变了我的asp.net code,从字典到列表中,然后加入相同的值。突然间,长度正常了。 ?!?!?!因此,对象不具有的长度在JavaScript?

推荐答案

对象没有一个长度属性,除非你给他们的。数组做,但阵列与创建 [] 不是 {}

Objects don't have a length property unless you give them one. Arrays do, but arrays are created with [] not {}.

如果你想知道有多少属性的对象了,你必须遍历他们,指望他们:

If you want to know how many properties an object has, you have to loop over them and count them:

var count = 0;
for (var foo in bar) {
    if (bar.hasOwnProperty(foo) {
        count++;
    }
}

这篇关于jQuery的AJAX JSON响应的长度是不确定的和不正确的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆