Javascript Ajax Jquery:如何返回结果?
在script-a.js中,我有以下功能:Javascript Ajax Jquery:如何返回结果?,javascript,jquery,ajax,Javascript,Jquery,Ajax,在script-a.js中,我有以下功能: function callGetAjax(url,callback) { $.get(url, {}, function(result) { // this will call the callback and pass the result callback(result); }); } 在script-b.js中,我称之为: var url = '/feed/locatio
function callGetAjax(url,callback) {
$.get(url, {}, function(result) {
// this will call the callback and pass the result
callback(result);
});
}
在script-b.js中,我称之为:
var url = '/feed/location';
callGetAjax(url,function(result)
{
//console.log(result); <= of course this logs right
data = result;
return data;
});
console.log(result); // <= ReferenceError: result is not defined
console.log(data); // <= ReferenceError: data is not defined
var url='/feed/location';
callGetAjax(url、函数(结果)
{
//console.log(result);Ajax是一种异步工具,因此您只能使用其中的数据。因此,如果您需要使用数据更改dom,您应该直接执行以下操作:
var url = '/feed/location';
callGetAjax(url,function(result)
{
//console.log(result); <= of course this logs right
data = result;
$('#some_dome_item').html(data);
});
var url='/feed/location';
callGetAjax(url、函数(结果)
{
//console.log(结果);看起来你不知道回调是如何工作的。我建议你仔细阅读。你不能从异步方法返回。这就像在线订购比萨饼并在它到达你家之前吃掉它。你不能返回。所有的逻辑都需要在回调执行时发生。因此,你需要将逻辑分解为多个部分。在好了,一切都好了,谢谢@epascarello