【问题标题】:jQuery .push into an Array in a .get call gives an empty resultjQuery .push 到 .get 调用中的数组给出了一个空的结果
【发布时间】:2012-03-29 10:37:33
【问题描述】:

谁能告诉我为什么下面给了我一个空字符串?当我在$.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);
    }

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    因为 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(href2, function(data){ content = contentArray.push(data); console.log(content); });作品。我试过 $.get(href2, function(data){ string = data.toString(); contentArray.push(string); });内容 = contentArray.toString();控制台日志(内容);但这不起作用
    • 那是因为.push() 追随console.log()
    • 我必须循环执行,因为我需要从多个页面收集数据,然后将其放入 1 个页面中
    • @Psylant - 我认为给出的答案是合适的,即使你想实现你的功能,那么你可以通过直接在页面上放置内容而不是接受变量来实现。替换'contentArray.push(string);' by '$(".somedivision").append(string)'
    • 是的,我知道你的意思,我实际上是这样工作的。但问题是我需要在内容转储到页面后让回调函数工作,因此我需要将内容加载到数组中,然后将其加载到 div 中,然后回调仅打印该 div。跨度>
    【解决方案2】:

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

    也就是说,$.get() 函数在不等待响应的情况下立即返回,你的整个 for 循环完成(排队多个 ajax 请求),然后你的 console.log() 发生在数组的哪个点仍然是空的。只有在那之后,才会调用任何 ajax 成功处理程序,无论 ajax 响应返回多快。

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

    【讨论】:

    • ahhh 好的,这是有道理的,所以如果我在那里说一个 if 语句执行一次 i>len 应该在 for 循环完成后执行?
    • 不,for 循环肯定会在任何成功回调运行之前完成,因此 if 语句将不起作用,除非您将 console.log() 移动到回调中并保持计数您收到的回复。看看我链接到的答案,并阅读 $.when () 方法。
    猜你喜欢
    • 1970-01-01
    • 2021-08-13
    • 2013-12-19
    • 2012-06-13
    • 1970-01-01
    • 1970-01-01
    • 2016-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多