Javascript 如何从ajax成功函数返回数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29794118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to return data from ajax success function?
提问by user3422637
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.
在我的前端 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.
How would I do this?
我该怎么做?
回答by Vikrant
Instead of returning datafrom success: pass datato a function.
而不是data从success:返回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
}
回答by atmd
ajax is by nature asyc. The code doesn't wait for the response from your successcallback, so the data isn't accessible outside of successunless passed.
ajax 本质上是 asyc。代码不会等待success回调的响应,因此success除非通过,否则无法在外部访问数据。
You'd need to handle the data inside the success, try calling a separate method/function:
您需要处理成功中的数据,请尝试调用单独的方法/函数:
function handleResponse(data) {
// do something with data
}
success:function(response_data_json) {
handleResponse(response_data_json.view_data);
}
here are the docs on jquery's ajax method
这是关于 jquery 的ajax 方法的文档
You could also just use an external success function rather then an annon inline that then calls the function anyway. it will still pass the data as a param
您也可以只使用外部成功函数而不是 annon 内联函数,然后无论如何调用该函数。它仍然会将数据作为参数传递
function handleResponse(data) {
// do something
}
$.ajax({
url:"/getDataFromServer.json",
//async: false,
type: "GET",
dataType: "json",
success:handleResponse
});
UPDATE: as pointed out in the comments, you might be better using a http getrequest rather then a post. they both have advantageshowever getrequests can be cached, so for retrieving data it might give a perf boost.
更新:正如评论中所指出的,使用http get请求而不是post. 它们都有优点,但是get可以缓存请求,因此对于检索数据,它可能会提高性能。

