Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
0
rated 0 times [  4] [ 4]  / answers: 1 / hits: 19558  / 14 Years ago, fri, february 4, 2011, 12:00:00

I have few functions, which calls another (integrated functions in browser), something like this:



function getItems () {
var xhr = new XMLHttpRequest();
xhr.open(GET, http://another.server.tld/, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
items = $(a[href^=/courses/], xhr.responseText);
}
};
xhr.send();
}


As I don't want to write more code inside and make each logical functionality separated, I need this function to return variable items.



I know there can happen some accidents (network/server is not available, has long-response...) and the function can return anything after gets data from the server or timeout occurs.


More From » callback

 Answers
28

This seems be an async request. I don't think you will be able to return data from this function.


Instead, you can take a callback function as an argument to this function and call that callback when you have the response back.


Example:


function getItems (callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://another.server.tld/", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
callback(xhr.responseText);
}
};
xhr.send();
}

[#93903] Wednesday, February 2, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
irvingcarloe

Total Points: 677
Total Questions: 109
Total Answers: 96

Location: Svalbard and Jan Mayen
Member since Sun, Sep 25, 2022
2 Years ago
irvingcarloe questions
Wed, Mar 31, 21, 00:00, 3 Years ago
Tue, Aug 4, 20, 00:00, 4 Years ago
Fri, Jul 3, 20, 00:00, 4 Years ago
;