在.get调用中将jQuery.prush推送到数组中会得到一个空结果

jQuery .push into an Array in a .get call gives an empty result

本文关键字:结果 一个 数组 jQuery get prush 调用      更新时间:2023-09-26

有人能告诉我为什么下面给了我一个空字符串吗?当我在$.get()回调函数中console.log(contentArray)时,它会显示数据,但当我尝试在下面代码中的位置执行时,结果是空的。

sectionArray = [];
contentArray = [];
$(function () {
    if (index == 1) {
        $('menu:eq(' + (section - 1) + ') li a').each(function () {
            sectionArray.push($(this).attr('href'));
        });
        var len = sectionArray.length;
        for (var i = 0; i < len; i++) {
            href2 = sectionArray[i];
            $.get(href2, function (data) {
                string = data.toString();
                contentArray.push(string);
            });
        }
        content = contentArray.toString();
        console.log(content);
    }

因为ajax请求在调用console.log()后结束,请尝试以下操作:

$.get(href2, function(data){
    string = data.toString();
    contentArray.push(string);
    content = contentArray.toString();
    console.log(content);
});

同样,在循环中执行ajax请求并不是最好的做法。这不会像您想要的那样工作。

更新:

jQuery还将async选项设置为false,您的代码应该可以工作,但工作速度会很慢。同步请求可能会暂时锁定浏览器。

更新2

也许可以试试这样的东西(也许不是那么好主意:D):

var countRequests = len;
$.get(href2, function(data){
    string = data.toString();
    contentArray.push(string);
    countRequests = countRequests - 1;
    if (countRequests == 0) {
        content = contentArray.toString();
        console.log(content);
        // or create callback
    }
});

问题是您的$.get() ajax请求是异步执行的。

也就是说,$.get()函数在不等待响应的情况下立即返回,整个for循环完成(将多个ajax请求排队),然后出现console.log(),此时数组仍然为空。只有在那之后,才会调用任何ajax成功处理程序,而不管ajax响应返回的速度有多快。

编辑:下面是另一个问题的答案,它显示了在所有ajax调用完成后如何做某事:https://stackoverflow.com/a/6250103/615754