如何从ajax成功函数返回数据? [英] How to return data from ajax success function?
本文介绍了如何从ajax成功函数返回数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的前端JavaScript应用程序中,我发出一个ajax请求来从服务器获取数据。一旦我获得数据,我想将该信息返回到视图。
In my front end JavaScript application, I make an ajax request to fetch data from the server. As soon as I get the data, I want to return that piece of information to the view.
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.
我该怎么做?
推荐答案
而不是从成功
返回数据
:传递数据
到函数。
Instead of returning data
from success
: pass data
to a function.
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
}
这篇关于如何从ajax成功函数返回数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文