Xhrio: return in callback.

94 views
Skip to first unread message

Rob Hofmeyr

unread,
Sep 16, 2010, 10:27:11 AM9/16/10
to Closure Library Discuss
Hi all,

Is there any way of returning an Xhrio request to a variable?

var response = goog.net.XhrIo.send("test.php", function(e) {
return e.target.getResponseJson();
});
alert(response);

The above returns undefined, I'm guessing because the static send
method doesn't return anything? Adding functionality to the callback
works but makes using the response in the original context difficult.
For example if I wanted to call the following function in place of the
alert():

myfunc(response, var1, var2);

Thanks for your time.

Nathan Naze

unread,
Sep 16, 2010, 12:20:58 PM9/16/10
to closure-lib...@googlegroups.com
The XHRs used in goog.net.XhrIo are always asynchronous (since
historically, in most browsers, a synchronous XHR blocks user input).
So you couldn't have a response in-line as you have written above (see
goog.net.XhrIo.prototype.send implementation).

If you wanted to get at the XhrIo itself, you can just instantiate
one. If you look at goog.net.XhrIo.send (the static one, not the
instance method), it's just a convenience wrapper that sets up the
necessary event listeners on the XhrIo.

Your handler needs to do your next step, and it'll get called when the
XHR completes successfully (if it doesn't fail). So, something like
this:

goog.net.XhrIo.send("test.php", function(e) {
myFunc(e.target.getResponseJson(), ...);
});

Hope that helps,

Nathan

Reply all
Reply to author
Forward
0 new messages