jQuery .push进入.get调用中的数组会产生一个空结果

问题描述:

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

Can anyone tell me why the below gives me an empty string? When I console.log(contentArray) in the $.get() callback function it shows the data but when I try to do it where it is in the code below, the result is empty.

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()之后结束试试这个:

because ajax request ends after you call console.log() try this:

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

在循环中做ajax请求也不是最好的事情。那不会按你的意愿工作。

also do ajax request in loop is not best thing to do. that wont work as you want.

UPDATE:

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

also jQuery has async option set to false and your code should work but will work slow. Synchronous requests may temporarily lock the browser.

更新2

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

maybe try something like this(maybe not so good idea :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
    }
});