use*_*637 12 javascript ajax jquery
在我的前端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.
Run Code Online (Sandbox Code Playgroud)
我该怎么做?
Vik*_*ant 19
而不是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
}
Run Code Online (Sandbox Code Playgroud)
ajax 本质上是 asyc。代码不会等待success
回调的响应,因此success
除非通过,否则无法在外部访问数据。
您需要处理成功中的数据,请尝试调用单独的方法/函数:
function handleResponse(data) {
// do something with data
}
success:function(response_data_json) {
handleResponse(response_data_json.view_data);
}
Run Code Online (Sandbox Code Playgroud)
这是关于 jquery 的ajax 方法的文档
您也可以只使用外部成功函数而不是 annon 内联函数,然后无论如何调用该函数。它仍然会将数据作为参数传递
function handleResponse(data) {
// do something
}
$.ajax({
url:"/getDataFromServer.json",
//async: false,
type: "GET",
dataType: "json",
success:handleResponse
});
Run Code Online (Sandbox Code Playgroud)
更新:正如评论中所指出的,使用http get
请求而不是post
. 它们都有优点,但是get
可以缓存请求,因此对于检索数据,它可能会提高性能。
归档时间: |
|
查看次数: |
64485 次 |
最近记录: |