简体   繁体   English

价值不会推向数组

[英]Value won't push to array

In the code below, I assign a value to a variable from JSON with this var tag = data[j]['text']; 在下面的代码中,我使用此var tag = data[j]['text'];为JSON中的变量赋值var tag = data[j]['text']; and I output it with this console.log(tag); 我用这个console.log(tag);输出它console.log(tag); (for testing) which works. (用于测试)哪些有效。

I try to push the values into an array with tags.push(tag); 我尝试使用tags.push(tag);将值推送到数组中tags.push(tag); but it WILL NOT WORK! 但它不会工作!

Why won't these values go into the array? 为什么这些值不会进入数组? I am just trying to get the contents of tag into an array... 我只是想把tag的内容放到一个数组中......

function GetAvailableTags() {
            var url = '/TextCodes/TextCodes?key=';
            var tagGroups = [];
            $('.ui-autocomplete-input').each(function () {
                var key = $(this).attr('id');
                var tags = [];
                //console.log(key);
                $.getJSON(url + key, function (data) {
                    for (var j = 0, len = data.length; j < len; j++) {
                        var tag = data[j]['text'];
                        console.log(tag);
                        tags.push(tag);
                    }
                });
                console.log(tags.length);
                for (var k = 0, len = tags.length; k < len; k++) {
                    console.log(tags[k]);
                }
            });
        }

Thanks for your help. 谢谢你的帮助。

Because $.getJSON is an asynchronous function. 因为$.getJSON是一个异步函数。 It means that your code 这意味着你的代码

console.log(tags.length);
for (var k = 0, len = tags.length; k < len; k++) {
    console.log(tags[k]);
}

will be executed before the $.getJSON callback function : 将在$.getJSON回调函数之前执行:

function () {
    var key = $(this).attr('id');
    var tags = [];
    //console.log(key);
    $.getJSON(url + key, function (data) {
        for (var j = 0, len = data.length; j < len; j++) {
            var tag = data[j]['text'];
            console.log(tag);
            tags.push(tag);
        }
    }

It is why your variable seems to be empty when look into in your code above, but how it is possible that the data are printed with console.log(tag); 这就是为什么在查看上面的代码时你的变量似乎是空的,但是如何用console.log(tag);打印数据呢console.log(tag); in the callback function. 在回调函数中。

Update 更新

Here is an example of using $.ajax method instead of $.getJSON to specify that the data must be retrieved synchronously using the parameter asynch : false 下面是使用$ .ajax方法而不是$ .getJSON来指定必须使用参数asynch同步检索数据的示例asynch : false

By that way, the server call response (success callback) is mandatory to continue the process. 通过这种方式,服务器调用响应(成功回调)是必需的,以继续该过程。 The disadvantage of this non-standard way is that your web page could be freezed waiting the server response. 这种非标准方式的缺点是您的网页可能会被冻结,等待服务器响应。 It is not the best elegant way to do that, but sometimes it is useful. 这不是最好的方式,但有时它很有用。

function GetAvailableTags() {
    var url = '/TextCodes/TextCodes?key=';
    var tagGroups = [];
    $('.ui-autocomplete-input').each(function () {
        var key = $(this).attr('id');
        var tags = [];
        //console.log(key);
        $.ajax({
            url: url + key,
            type: 'POST',
            asynch: false,//specify to stop JS execution waiting the server response
            success: function (data) {
                for (var j = 0, len = data.length; j < len; j++) {
                    var tag = data[j]['text'];
                    console.log(tag);
                    tags.push(tag);
                }
            },
            error : function(jqXHR, textStatus, errorThrown) {
                alert('an error occurred!');
            }
        });
        console.log(tags.length);
        for (var k = 0, len = tags.length; k < len; k++) {
            console.log(tags[k]);
        }
    });
}

My solution is kind of long and stupid, but it works. 我的解决方案有点长而且很愚蠢,但它确实有效。 Now, I can access the variables like an array textCodes['taxes'] . 现在,我可以像数组textCodes['taxes']一样访问变量。 sdespont's async note helped, too. sdespont的async笔记也有帮助。

    var textCodes = GenerateTextCodes();
    console.log(textCodes);

    function GenerateTextCodes() {
        var arr = [];
        $('.ui-autocomplete-input').each(function () {
            var id = $(this).attr('id');
            arr[id] = GetAvailableTags(id);
        });
        //console.log(arr['taxes']);
        return arr;
    }

    // get all autocomplete element IDs and put them into an array
    function GetAvailableTags(key) {
        var url = '/TextCodes/TextCodes?key=';
        var tags = [];
        $.ajax({
            url: url + key,
            type: 'GET',
            async: false,
            success: function (data) {
                //console.log(data[0].text);
                //console.log(data.length);
                for (var i = 0; i < data.length; i++) {
                    //console.log(data[i].text);
                    tags.push(data[i].text);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert('an error occurred!');
            }
        });
        //console.log(tags);
        return tags;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM