如何从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. 

我该怎么办?

而不是从success返回data :将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 } 

ajax本质上是asyc。 代码不会等待success回调的响应,因此除非通过,否则无法在success之外访问数据。

您需要处理成功内部的数据,尝试调用单独的方法/函数:

 function handleResponse(data) { // do something with data } success:function(response_data_json) { handleResponse(response_data_json.view_data); } 

这里是关于jquery的ajax方法的文档

您也可以使用外部成功函数,而不是内联,然后调用函数。 它仍然会将数据作为参数传递

 function handleResponse(data) { // do something } $.ajax({ url:"/getDataFromServer.json", //async: false, type: "GET", dataType: "json", success:handleResponse }); 

更新:正如评论中所指出的,您可能更好地使用http get请求而不是post 。 它们都有优势,但是可以缓存请求,因此对于检索数据,它可能会提供性能提升。