2016-02-05 85 views
1

之前变量我有这样的代码:如何定义AJAX调用

function aaa(){ 
    var db_data; 
    $.ajax({ 
     url: "http://localhost:8888/aaa/{{$article->id}}", 
     type: "GET", 
     async: true, 
     dataType: "json", 
     success: function(data) { 
      db_data = data; 
      console.log(db_data); 
     }, 
     error: function (data) { 
      console.log(data); 
      console.log('GRESKA NEKA'); 
     }  
    }); 
    console.log(db_data); 
}; 

但后来我得到至少线console.log(aaa) - >不确定...

为什么?第一个console.log工作正常但在ajax之外我无法获得db_data ... WHy?

+0

您正在订购比萨饼,然后尝试在它交付之前将其吃掉! Ajax是一个异步调用,在最后一个'console.log'执行后,'success'会被调用回去。 –

+0

如何解决? – MonkeyBusiness

+0

只使用数据*里面的*回调(或使用承诺)。问题是“接下来你想怎么处理数据?” –

回答

2

您正在订购比萨饼,然后尝试在它交付之前将其吃掉! Ajax是一个异步调用,并且success在最后执行console.log后得到回调。

您只需要在回调中使用异步数据。

另一种方法是使用由阿贾克斯返回promise所以你的代码变成一个功能,“承诺返回数据”:

// Return the Ajax promise 
function aaa() { 
    return $.ajax({ 
    url: "http://localhost:8888/aaa/{{$article->id}}", 
    type: "GET", 
    async: true, 
    dataType: "json", 
    }); 
} 

// and use like this 

aaa().then(function(data){ 
    // Do something with the data 
}).fail(function(data){ 
    // Do something with the data when it fails 
}); 

承诺让功能重用。