2011-12-26 75 views
1

可能重複:
Why is this function returning 「undefined」?如何讓JavaScript函數返回Ajax結果?

假設我有以下JS功能:

function getTileData(x, y, loc_slug) { 
    $.ajax({ 
     url: "/sys/map-admin/show-location/"+loc_slug+"/get-tile/"+x+"-"+y+"/", 
     success: function(data){ 
      alert(data); // Object, that's correct. 
      **What do I need to make the whole getTileData function return data?** 
     } 
    }); 
} 

,我把它叫做另一個函數內的類似

tile = getTileData(1, 2, 'asd'); 
alert(tile); // undefined 

回答

0

可以將async屬性設置爲false(默認爲true)。

腳本將被暫停,直到請求完成。

function getTileData(x, y, loc_slug) { 

    var data; // create variable in getTileData scope; 
    $.ajax({ 
     async: false, // 
     url: "/sys/map-admin/show-location/"+loc_slug+"/get-tile/"+x+"-"+y+"/", 
     success: function(d){ 
      data = d; // write ajax result to `data` variable to be available outside this callback; 
     } 
    }); 
    return data; 
}