Returning variable from onreadystatechange
I am trying to return a variable from onreadystatechange and seem to be having trouble with scope. Even if I set a global variable, when tr开发者_开发百科ying to retrieve my variable after the fact, its undefined. Not quite sure what I am doing wrong. I haven't done too much work with Javascript in the past 3 years.
var lat;
var lon;
window.onload = function dosomething(){
var myRequst = new XMLHttpRequest();
var url = "http://www.instamapper.com/api?action=getPositions&key=584014439054448247";
myRequst.open('get', url);
myRequst.onreadystatechange = function(){
if ((myRequst.readyState == 4) && (myRequst.status == 200)){
//alert(myRequst.responseText);
var data = myRequst.responseText;
collected=data.split(","); //parses the data delimited by comma and put data into array
lat = collected[4];
lon = collected[5];
document.write("latitude "+lat+"<BR>\n");
document.write("latitude "+lon+"<BR>\n");
}
}
myRequst.send(null);
}
document.write(lat);
Any help or suggestions would be much appreciated.
Is the only way of returning more than one item by using an object? Like such?
myRequest.onreadystatechange = function() {
if(myRequest.readyState == 4 && myRequest.status == 200) {
var obj;
obj.latitude = collected[4];
obj.longitude = collected[5];
getdata(obj);
}
}
function getdata(obj)
{
lat = obj.latitude;
lon = obj.longitude;
document.write(lon);
document.write(lat);
}
You have to use a callback function which will handle the data. Remember AJAX stands for Asynchronous(JAX). So if after your onreadystatechange
handling the value is not yet available is because the request did not complete at that moment.
myRequest.onreadystatechange = function() {
if(myRequest.readyState == 4 && myRequest.status == 200) {
(function(data) {
// do something with the response in the variable data
})(myRequest.responseText);
}
}
Edit: also you can follow the request in the net/console tab of firebug to see exactly if an error has occured
精彩评论