ajax 调用后,如何更改包装器 JavaScript 函数中的全局变量? [英] How do I change a global variable in the wrapper JavaScript function after an ajax call?
问题描述
function ajax_test(str1){
var url = "None"
jq.ajax({
type:'post',
cache: false,
url: 'http://....' + str1,
success: function(data, status, xhr){
url=data;
},
error: function (xhr, status, e) {
},
async: true,
dataType: 'json'
});
return url
}
如何设置全局变量url
为返回的成功ajax数据?
How can I set the global variable url
to be the returned success ajax data?
推荐答案
在 Javascript 中,函数不可能返回
异步结果.该函数通常会在发出 AJAX 请求之前返回.
In Javascript, it is impossible for a function to return
an asynchronous result. The function will usually return before the AJAX request is even made.
您总是可以强制您的请求与 async: false
同步,但这通常不是一个好主意,因为它会导致浏览器在等待结果时锁定.
You can always force your request to be syncronous with async: false
, but that's usually not a good idea because it will cause the browser to lock up while it waits for the results.
解决这个问题的标准方法是使用回调函数.
The standard way to get around this is by using a callback function.
function ajax_test(str1, callback){
jq.ajax({
//... your options
success: function(data, status, xhr){
callback(data);
}
});
}
然后你可以这样称呼它:
and then you can call it like this:
ajax_test("str", function(url) {
//do something with url
});
这篇关于ajax 调用后,如何更改包装器 JavaScript 函数中的全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!