Sunday, June 2, 2024
133
rated 0 times [  135] [ 2]  / answers: 1 / hits: 36575  / 14 Years ago, sat, march 19, 2011, 12:00:00

I'm new to JavaScript programming. I'm now working on my Google Chrome Extension. This is the code that doesn't work... :P



I want getURLInfo function to return its JSON object, and want to put it into resp. Could someone please fix my code to get it work?



function getURLInfo(url)
{
var xhr = new XMLHttpRequest();
xhr.open
(
GET,
http://RESTfulAPI/info.json?url=
+ escape(url),
true
);
xhr.send();
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4)
{
return JSON.parse(xhr.responseText);
}
}
}
var resp = getURLInfo(http://example.com/) // resp always returns undefined...


Thanks in advance.


More From » xmlhttprequest

 Answers
25

You are dealing with an asynchronous function call here. Results are handled when they arrive, not when the function finishes running.



That's what callback functions are for. They are invoked when a result is available.



function get(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open(GET, url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
// defensive check
if (typeof callback === function) {
// apply() sets the meaning of this in the callback
callback.apply(xhr);
}
}
};
xhr.send();
}
// ----------------------------------------------------------------------------


var param = http://example.com/; /* do NOT use escape() */
var finalUrl = http://RESTfulAPI/info.json?url= + encodeURIComponent(param);

// get() completes immediately...
get(finalUrl,
// ...however, this callback is invoked AFTER the response arrives
function () {
// this is the XHR object here!
var resp = JSON.parse(this.responseText);

// now do something with resp
alert(resp);
}
);


Notes:




  • escape() has been deprecated since forever. Don not use it, it does not work correctly. Use encodeURIComponent().

  • You could make the send() call synchronous, by setting the async parameter of open() to false. This would result in your UI freezing while the request runs, and you don't want that.

  • There are many libraries that have been designed to make Ajax requests easy and versatile. I suggest using one of them.


[#93188] Thursday, March 17, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
pranavrorys

Total Points: 466
Total Questions: 87
Total Answers: 115

Location: Barbados
Member since Sun, Nov 27, 2022
2 Years ago
pranavrorys questions
Fri, May 27, 22, 00:00, 2 Years ago
Thu, Oct 28, 21, 00:00, 3 Years ago
Sat, May 30, 20, 00:00, 4 Years ago
Fri, Dec 20, 19, 00:00, 5 Years ago
;