带回调函数的AJAX

时间:2010-08-22 02:50:58

标签: javascript ajax

我无法在ajax连接中访问数据。不确定我的代码有什么问题。好像它永远不会达到第二个功能。有什么想法吗?

function fetchgps(callback)
{
  var url = "http://www.instamapper.com/api?action=getPositions&key=584014439054448247";

  var myRequest = new XMLHttpRequest();
  myRequest.onload = function(e) {xml_loaded(e, myRequest, callback);}
  myRequest.open("GET", url);
  myRequest.setRequestHeader("Cache-Control", "no-cache");
  myRequest.setRequestHeader("wx", "385");
 myRequest.send(null);

 return myRequest;
}

function xml_loaded(event, request, callback)
{
 if (request.responseText){
  var obj = {error:false, errorString:null}

   var data = myRequest.responseText;
   collected=data.split(",");   //parses the data delimited by comma and put data into array

obj.latitude = collected[4];
obj.longitude = collected[5];

callback(obj);
  }

  else
{
callback ({error:true, errorString:"XML request failed. no responseXML"}); //Could be any number of things..
}

}

function dealwithgps(obj)
{
lat = obj.latitude;
lon = obj.longitude;
document.write(lon);
document.write(lat);
}

fetchgps(dealwithgps);

1 个答案:

答案 0 :(得分:3)

多出request.onreadystatechange而不是request.onload

function fetchgps(callback)
{
  var url = 
   "http://www.instamapper.com/api?action=getPositions&key=584014439054448247";

  var myRequest = new XMLHttpRequest();
  // myRequest.onload = function(e) {xml_loaded(e, myRequest, callback);}
  myRequest.onraedystatechange = function() { //onraedystatechange instead of onload!!
    xml_loaded(myRequest, callback);
  }
  myRequest.open("GET", url);
  myRequest.setRequestHeader("Cache-Control", "no-cache");
  myRequest.setRequestHeader("wx", "385");
 myRequest.send(null);

 return myRequest;
}

function xml_loaded(request, callback) {
   if(request.readyState === 4) {
       //... only then do your processing
   }
}