javascript - Best practices for attaching a variable to XMLHttpRequest? -


var xhr=new xmlhttprequest(); xhr.open('get','example.php'); xhr.myvar=0; xhr.onreadystatechange=function(){   this.myvar=this.responsetext.length;   var s=this.readystate+":"+this.myvar+":"+this.responsetext;   document.getelementbyid('x').innerhtml=s;   }; 

i have script on web page (and <p id="x"></p>). want attach variable use in onreadystatechange function (obviously, in real code more interesting here).

this works fine in browsers i've tried in, makes me nervous. there convention should following? e.g. prefix custom variables underline, or that?

btw, attaching member variable otherwise feels right: main alternative use global variable, don't @ (i might have 2 xmlhttprequest objects on page).

you can use closures.

assuming ajax request inside function body, can declar myvar using var keyword , use inside onreadystatechange function if local variable.

function x() {      ....     ....      var xhr = new xmlhttprequest();     xhr.open('get', 'example.php');     var myvar = 0;     xhr.onreadystatechange = function() {         this.myvar = this.responsetext.length;         var s = this.readystate + ":" + myvar + ":" + this.responsetext;         document.getelementbyid('x').innerhtml = s;     };      ....     ....  } 

Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -