簡體   English   中英

返回$ .get的結果不返回任何內容

[英]Return the result of $.get returns nothing

我有一個將返回JSON的函數。 在調用函數中檢查返回的數據時,發現未定義。

我唯一能想到的是ajax是異步的,它沒有等待數據返回。 因為這可能是第二個警報框在第一個警報之前觸發的唯一原因。

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

現在我該如何解決呢?

不要返回數據,在expandSearch執行成功回調中需要做的事情。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM