简体   繁体   中英

Return the result of $.get returns nothing

I have a function which will return a JSON back. When checking the returned data in the calling function it was found to be undefined.

Only thing I can think of is ajax is async and it didn't wait for the data to be returned. Cuz that could be the only reason why the second alert box got triggered before the first alert.

$.get( '/search/s/g/' , { 'q' : query } , function(data) {
    var result = $.parseJSON(data);
    if ( result.length < 10 ) { 
        data2 = extendSearch(query);
        alert("second"); // This got triggered first.
    }
    populateSearchResult(result);
});

function extendSearch(q) {
    $.get('/search/s/f/', { 'q': q }, function(data) { 
         alert("first"); // This got triggered as the second alert box
         return data;
    });
}

Now how do i solve this?

Don't return data, In expandSearch do what you need to do inside the success callback.

function expandSearch(q) {
    $.get('/search/s/f/', { 'q': q }, function(data) { 
         alert("first"); // This got triggered as the second alert box
         // do something with the data here
         // modify dom or w/e
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM