2011-12-26 76 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; 
}