onreadystatechange的不叫在Firefox [英] onreadystatechange is not called in firefox
问题描述
下面是我的codeS。
Here are my codes.
我的函数来发送Ajax请求并返回一个值:
my function to send ajax request and return a value:
function myAjaxCall(){
var myValue=0
var async= false //I have to use synchronized request(otherwise my return value is 0)
xmlhttp.open("GET",URL,async);
xmlhttp.onreadystatechange=function(){
...
myValue = SOMEVALUE;
};
xmlhttp.send();
return myValue
}
我的其他功能将使用返回myAjaxCall函数值
My other function will use the myAjaxCall function returned value
function otherFunc(){
var x= myAjaxCall();
}
事情是可以正常使用这种方式,除了在火狐浏览器,我知道的原因是因为在Firefox中,如果我使用同步要求,的onreadystatechange
将不会被调用。
Things are working perfectly in this way except on Firefox browser, I know the reason is because in Firefox, if I use synchronized request, the onreadystatechange
will not be called.
在我的情况,但是,我必须使用同步 Ajax请求,否则 myAjaxCall()
返回的函数值总是initail值 VAR myvalue的= 0
In my case, however, I have to use synchronized ajax request, otherwise myAjaxCall()
function returned value is always the initail value "var myValue=0
".
如何摆脱这个Firefox的问题?
How to get rid of this firefox problem??
推荐答案
使用一个函数指针,而不是一个内联函数,以避免此问题:
Use a function pointer instead of an inline function to avoid this issue:
function myAjaxCall(){
var myValue=0;
var async= true;
xmlhttp.open("GET",URL,async);
xmlhttp.send();
xmlhttp.onreadystatechange=foo;
}
function foo(bar)
{
var myValue = SOMEVALUE;
return myValue;
}
功能的控制范围,JavaScript,因此:
Functions control scope in JavaScript, so:
- 在匿名函数创建一个新的范围,而引用的功能是在全球范围内
- 移动功能超出范围避免了命名空间冲突
- myvalue的继承了新的范围值,虽然它没有在全球范围内
此外,发应的onreadystatechange之前完成
Also, send should be done before onReadyStateChange
这篇关于onreadystatechange的不叫在Firefox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!