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

后端 未结 2 548
眼角桃花
眼角桃花 2021-01-26 13:32

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

2条回答
  •  无人共我
    2021-01-26 14:03

    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);
    });
    

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

    UPDATE:

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

    UPDATE 2

    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
        }
    });
    

提交回复
热议问题