jQuery 成功的 getJSON 操作后 data.length 未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9428190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:47:51  来源:igfitidea点击:

data.length is undefined following a successful getJSON operation

jqueryjsoneach

提问by Jamie Hartnoll

I'm populating a drop down with JSON data from getJSON.

我正在使用 getJSON 中的 JSON 数据填充下拉列表。

Populating is working fine, but trying to establish that it's finished by comparing to data.lengthis not working as data.lengthis undefinedand I can't see why!

填充工作正常,但试图建立通过比较,它的结束data.length并不像工作data.lengthundefined,我不明白为什么!

The data looks like:

数据看起来像:

{
    "1": {
        "id": "1",
        "name": "Plymouth"
    },
    "2": {
        "id": "2",
        "name": "Torquay"
    }
}

My code looks like:

我的代码看起来像:

$('.locationList').empty();
$('.locationList').append('<option value="">Select...</option>');
$.getJSON('/Settings/locations.txt', function (data) {
    var dataNum = data.length;
    var counter = 1;
    $.each(data, function (i, item) {
        $('.locationList').append('<option value="' + data[i].id + '">' + data[i].name + '</option>');
        if (counter >= dataNum) {
            $('#bookTo').val(locationID + 1);
            $('#transferFrom').val(locationID);
        };
        counter++;
    });
});

This section:

这个部分:

if (counter >= dataNum) {
    $('#bookTo').val(locationID + 1);
    $('#transferFrom').val(locationID);
};
counter++;

Is meant to allow me to preset the values of the drop down boxes once the $.eachloop has completed (this works with other lists), but it's not happening.

旨在允许我在$.each循环完成后预设下拉框的值(这适用于其他列表),但它没有发生。

When I run alert(data.length)I get undefinedwhich makes no sense as dataclearly does have a lengthin order for it to populate the drop down box properly through the $.each, which it does!

当我运行时,alert(data.length)我得到undefined这毫无意义,因为它data显然有一个length,以便它通过 正确填充下拉框$.each,它确实做到了!

EDIT: sorry, should add, the variable locationIDis declared earlier in the script from a Cookie and IS valid

编辑:抱歉,应该补充一下,该变量locationID是在脚本中较早地从 Cookie 中声明的,并且是有效的

回答by andlrc

This is an object:

这是一个对象:

data = {
    "1": {
        "id": "1",
        "name": "Plymouth"
    },
    "2": {
        "id": "2",
        "name": "Torquay"
    }
}

and it doesn't have a lengthproperty.

它没有length财产。

see: only the property 1and 2.

请参阅:仅属性12

Are you sure you want it as an object rater then an array:

您确定要将其作为对象评估器,然后是数组:

data = [
    {
        "id": "1",
        "name": "Plymouth"
    },
    {
        "id": "2",
        "name": "Torquay"
    }
]

then you have the lengthproperty and a lot of other native array methods like sort. And you can access your data like this:

那么你就有了这个length属性和许多其他的原生数组方法,比如sort. 您可以像这样访问您的数据:

data[0]

witch is equal to:

女巫等于:

{
    "id": "1",
    "name": "Plymouth"
}

回答by adeneo

Probably not the best way of doing this, but something like this could probably be a quick fix?

可能不是这样做的最佳方式,但像这样的事情可能是一个快速解决方案?

$('.locationList').empty();
$('.locationList').append('<option value="">Select...</option>');
$.getJSON('/Settings/locations.txt', function (data) {
    var dataNum = 0;
    for (i in data) {if (data.hasOwnProperty(i)) {dataNum++;}}    
    var counter = 1;
    $.each(data, function (i, item) {
        $('.locationList').append('<option value="' + data[i].id + '">' + data[i].name + '</option>');
        if (counter >= dataNum) {
            $('#bookTo').val(locationID + 1);
            $('#transferFrom').val(locationID);
        };
        counter++;
    });
});

回答by andreapier

Your JSON:

你的 JSON:

{"1":{"id":"1","name":"Plymouth"},"2":{"id":"2","name":"Torquay"}}

is an object, not an array so the lengthproperty is not defined. If you want to parse it as an array your server needs to give a response like:

是一个对象,而不是数组,因此length未定义该属性。如果您想将其解析为数组,您的服务器需要给出如下响应:

{"response": [{"1":{"id":"1","name":"Plymouth"}},
{"2":{"id":"2","name":"Torquay"}}] }

with []instead of {}

[]代替{}

回答by Dalio Braga

When response.data == [], this works:

当 response.data == [] 时,这有效:

if (response.data.length === 0)

This is a Array then has length prospriety.

这是一个数组,然后有长度繁荣。