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

后端 未结 2 540
眼角桃花
眼角桃花 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 13:57

    The problem is that your $.get() ajax requests are executed asynchronously.

    That is, the $.get() function returns immediately without waiting for the response, your entire for loop completes (queueing up multiple ajax requests), then your console.log() occurs at which point the array is still empty. Only after that do any of the ajax success handlers get called, regardless of how fast the ajax responses come back.

    EDIT: Here is an answer from another question that shows how to do something after all the ajax calls have completed: https://stackoverflow.com/a/6250103/615754

    0 讨论(0)
  • 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
        }
    });
    
    0 讨论(0)
提交回复
热议问题