小编典典

如何从ajax成功函数返回数据?

ajax

在我的前端JavaScript应用程序中,我发出了ajax请求以从服务器获取数据。一旦获得数据,我想将该信息返回给视图。

var view_data;
$.ajax({
    url:"/getDataFromServer.json",
    //async: false,
    type: "POST",
    dataType: "json",
    success:function(response_data_json) {
        view_data = response_data_json.view_data;
        console.log(view_data); //Shows the correct piece of information
        return view_data; // Does not work. Returns empty data
    }
 });

 // return view_data; --> Keeping the return outside of the ajax call works but then I need to make my ajax call synchronous in order for this return clause to be executed after the ajax call fetches data.

我该怎么做?


阅读 329

收藏
2020-07-26

共1个答案

小编典典

而不是datasuccess:返回来传递data给函数。

var view_data;
$.ajax({
    url:"/getDataFromServer.json",
    //async: false,
    type: "POST",
    dataType: "json",
    success:function(response_data_json) {
        view_data = response_data_json.view_data;
        console.log(view_data); //Shows the correct piece of information
        doWork(view_data); // Pass data to a function
    }
 });

function doWork(data)
{
    //perform work here
}
2020-07-26