A standard ajax request is used (self-written (!) Not jquery), which are many on the Internet. Everything works great, but the result can not be denied (return). It can be output by alert (alert), it can be written in div ( $('content').innerHTML = result; ), but it cannot be returned from the function. Why?

Code:

 ajax.get = function (url) { var XMLHttp = createXmlHttp(); XMLHttp.open("get", url, true); XMLHttp.send(null); XMLHttp.onreadystatechange = function () { if (XMLHttp.readyState == 4) { if (XMLHttp.status == 200) { var qR = XMLHttp.responseText; * * return qR; * * << < ------возвращаетundefined } else { alert("error!_!"); } } } } 

    2 answers 2

    everything is very simple, read about asynchronous code execution:

     var qR; XMLHttp.onreadystatechange = function () { if (XMLHttp.readyState == 4) { if (XMLHttp.status == 200) { qR = XMLHttp.responseText; } else { alert("error!_!"); } } } $('content').innerHTML = qR; // примерно так 

    UPD1:

    I say, read about asynchronous code execution, in your case it is necessary to transfer the second parameter in ajax.get callback, which in it to execute, updated the answer

     ajax.get = function (url, callback) { var XMLHttp = createXmlHttp(); XMLHttp.open("get", url, true); XMLHttp.send(null); XMLHttp.onreadystatechange = function () { if (XMLHttp.readyState == 4) { if (XMLHttp.status == 200) { callback(XMLHttp.responseText); } else { alert("error!_!"); } } } } 

    and call as follows:

     ajax.get(/*url*/, function(resp){ $('content').innerHTML = resp; }) 
    • not. a little misunderstood me. I need the following to happen: $ ('content'). InnerHTML = ajax.get ('blablabla'); so that with such a call, the AJAX would be called with a parameter and return the data by inserting it there where I assign it. so it returns undefined - dolphin4ik
    • 2
      I say, read about asynchronous code execution, in your case it is necessary to transfer the second parameter in ajax.get callback, which in it to execute, updated the answer - Specter
    • I understand that no mega tricky way will not exactly return the value? Just desperately need a design with the return. - dolphin4ik
    • one
      I asked Google (on my own behalf, not on yours). He gave a bunch of links. Here are two: hunlock.com/blogs/Snippets:_Synchronous_AJAX stackoverflow.com/questions/133310/… - alexlz

    The ajax request may be synchronous, but then the browser will freeze while the data is being requested, which is not good

    • "When you can not, but really want - you can." Here either hang, or not return the result, which is not yet - alexlz
    • Yes, I knew that. Thought can human cunning will force asynchronous all the same .. THANK YOU. Topic closed - dolphin4ik