[Javascript] return value from "ajax"/ function

Howard Jess hjess at cardomain.com
Fri Dec 8 16:38:16 CST 2006




"Brian L. Matthews" <blmatthews at gmail.com> wrote:

>>function requestFile(url)
>>{
>>httpRequest.open('get', url, true);
>>httpRequest.onreadystatechange = function() { handleRequest() };
>>httpRequest.send(null);
>>}
>>...
>>var foo = requestFile(...);
>>
>>the handleRequest() function gets the data and when it's ready 
>>loaded, and only then(!), requestFile() should return the data for 
>>the var foo.
>>
>>how can I do this?!
>
>You can't. The request runs asynchronously (the first 'A' in Ajax :-) 
>). requestFile returns immediately (with undefined in your example), 
>then at various stages in the request's lifetime, your handleRequest 
>function will be called. When the request is complete, handleRequest 
>should do whatever needs to be done with the response.

Well, yes you can; AJAX's 'A'synchronicity is optional. Change your
function (completely off the top of my head, untested, no error
checking, etc.) to:

function requestFile(url) {
  httpRequest.open('get', url, false);
  httpRequest.send(null);  // synchronous; returns when response is complete
  return httpRequest.responseText;
}


--
hj



More information about the Javascript mailing list