异步Ajax调用工作不正常 [英] async-ajax call not working as expected
问题描述
设置:
我在做一个Ajax JSONP调用,这是工作的罚款。这样做的回调函数改变一个变量,myVaraible的价值。只是该呼叫后,有一些if-else逻辑其中工程上的myVaraible的值。
I am doing an ajax-jsonp call, which is working fine. The callback function of this changes value of a variable, "myVaraible". Just after the call, there is some if-else logic which works on the value of "myVaraible".
下面是code:
<script>
function myfunction() {
$.ajax({
url: myURL,
dataType: "jsonp",
jsonp : "jsonp",
async: false,
jsonpCallback: "jsonpCallbackFn"
});
}
function jsonpCallbackFn(mydata) {
alert("inside jsonpCallbackFn");
if(something) {
// change value of a variable "myVariable";
}
}
$(document).ready(function() {
$("#preview_button").mouseover(function() {
myfunction();
alert("after myfunction");
// do some if-else logic based upon the value of myVariable which is updated by the call to myfunction()
});
});
</script>
的问题:
Ajax调用仍然悬而未决,控制转移到了的if-else块(有效地执行关于myVariable的旧/过时的值)。然后Ajax调用完成。总之,出了2 警告
框,警报(之后MyFunction的);
执行,然后再警报(内jsonpCallbackFn);
The ajax call remains 'pending', the control moves to the if-else block (effectively executing on the old/stale value of myVariable). And then the ajax call completes. In short, out of the 2 alert
boxes, alert("after myfunction");
executes first and then alert("inside jsonpCallbackFn");
正如你所看到的,我已经设置异步:假的,
,不过貌似是不按预期工作。谁能告诉我,我究竟做错了什么?另外,我不知道我是否已经正确地解释整个方案,请让我知道是否需要任何更多的信息。
As you can see, I have already set async: false,
, but looks like that is not working as expected. Can anyone tell me what am I doing wrong? Also, I am not sure if I have explained the entire scenario properly, please let me know if any more info is needed.
多谢了。
推荐答案
从 $就一>文档:
跨域请求和数据类型:JSONP请求不支持同步操作
Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation
所以,你需要把任何依赖回调请求的结果。
So, you'll need to put anything that relies on the results of the request in the callback.
这篇关于异步Ajax调用工作不正常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!