onreadystatechange is not called in firefox

让人想犯罪 __ 提交于 2019-12-24 01:16:45

问题


Here are my codes.

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
}

My other function will use the myAjaxCall function returned value

function otherFunc(){
   var x= myAjaxCall();
}

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.

In my case, however, I have to use synchronized ajax request, otherwise myAjaxCall() function returned value is always the initail value "var myValue=0".

How to get rid of this firefox problem??


回答1:


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;
  }

Functions control scope in JavaScript, so:

  • The anonymous function creates a new scope, while the referenced function is in the global scope
  • Moving the function out of scope avoids the namespace conflict
  • myValue inherits a value in the new scope, while it does not in the global scope

Also, send should be done before onReadyStateChange



来源:https://stackoverflow.com/questions/4958387/onreadystatechange-is-not-called-in-firefox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!