javascript - Is there a way to change a global variable on the document in the call back xmlHttpReq.onreadystatechange? -


i pretty new ajax thing, want set value global variable on document based on status changed in call function xmlhttpreq.onreadystatechange, used

function checkfile(fileurl) {     var xmlhttpreq = false;     var self = this;         // mozilla/safari     if (window.xmlhttprequest) {         self.xmlhttpreq = new xmlhttprequest();     }     // ie     else if (window.activexobject) {         self.xmlhttpreq = new activexobject("microsoft.xmlhttp");     }      if(self.xmlhttpreq == null){     alert("your browser not support xmlhttpreq")     }      self.xmlhttpreq.open('head', fileurl, true);     self.xmlhttpreq.onreadystatechange = function() {         if (self.xmlhttpreq.readystate == 4) {             if (self.xmlhttpreq.status == 200) {           window.rett = 1;         //alert(window.rett);            } else if (self.xmlhttpreq.status == 404) {           window.rett = 0;         //alert(window.rett);             }         }     }     self.xmlhttpreq.send();  } 

and use checkfile in jquery template this:

<script id="resulttemplate" type="text/x-jquery-tmpl">          <li> ${checkfile(link)} <b> {{if window.rett ==  1 }} ${link}   {{/if}}</b> </li>      </script> 

but when access window.rett in jquery template, says undefined...

the reason want global value want generate different gui based on global value.

maybe not practice of using global variable? suggestion appreciated.

most because time tried accessing it, ajax request has not completed yet (has not reached state 4), global hasn't been declared (or if was, still contains value of previous result)

i suggest use template within callback. way, time template checks value, value there:

function yourajaxfunction(arg1, arg2,...,callback){    //all ajax setup codes here    if (self.xmlhttpreq.readystate === 4) {     if (self.xmlhttpreq.status === 200) {        //sending callback 1       callback(1);     } else if (self.xmlhttpreq.status === 404) {        //sending callback 1       callback(0);     }   }    //ajax send codes  }  //how should use yourajaxfunction(arg1,arg2,...,function(rett){   //use rett here   //parse template here }); 

Comments

Popular posts from this blog

ios - iPhone/iPad different view orientations in different views , and apple approval process -

java Extracting Zip file -

C# WinForm - loading screen -