Reputation: 47
Trying to get my head around http requests and asynchronous javascript behaviour.
function httpGetAsync(url, callback){
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
console.log(xmlHttp.responseText); // prints the ip address
callback(xmlHttp.responseText);
}
}
xmlHttp.open("GET", url, true)
xmlHttp.send(null);
}
httpGetAsync("http://httpbin.org/ip", function(){
console.log(this); // doesn't print the ip address
})
The http request is just a simple one that returns a json formatted ip address of the get request. In the function definition the ip address can be printed to the console just fine however in the callback the console prints out the window object. this
is probably the wrong thing to use, how do I access the data in xmlHttp.responseText
in the callback?
Upvotes: 0
Views: 3676
Reputation: 324790
You're calling callback(xmlHttp.responseText)
, so...
httpGetAsync("...", function(response) {
console.log(response);
});
Simple!
One small point: I would recommend putting the .open
call before the onreadystatechange
, because in some (older) browsers calling .open
will reset event handlers.
Upvotes: 1
Reputation: 944425
callback(xmlHttp.responseText);
You are calling a function. You are passing it an argument.
function(){ console.log(this); // doesn't print the ip address }
Your function is not expecting to receive any arguments. Change that, then use that argument.
function(my_argument){
console.log(my_argument);
}
See also How does the “this” keyword work?
Upvotes: 1