简体   繁体   中英

AJAX send post request,can't return the value to other function?

I want to return a json object from the onreadystatechange = function(){}, but I failed. Could you provide me a method to do this? for example, when I call the function getIntervention(startdate,enddate).Then where will the json data in the "onreadystatechange = function(){}" return?

[code=JScript][/code]
function getIntervention(startdate,enddate)
{
var xmlhttp = false;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  if (XMLHttpRequest.overrideMimeType)
  {
  XMLHttpRequest.overrideMimeType("text/xml");
  }
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
if(!xmlhttp)
 {
window.alert("can't create!");
return false;
}   
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
  {
  var jsondata=eval('('+xmlhttp.responseText+')');
  document.getElementById("myDiv").innerHTML=jsondata.nbMissions;
  ***return jsondata;***
  }
  else
document.getElementById("myDiv").innerHTML=xmlhttp.status+"-"+xmlhttp.readyState;
  }
xmlhttp.open("POST","proxy.jsp",true);
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlhttp.send("url=http://aqueduc.kelcode.com/proc/gw.php&requestName=getIntervention&uid=UID_GATEWAY&startDate="+startdate+"&endDate="+enddate+"");
}

You simply can't return results from asynchronous methods.

The only thing you can do is to queue up another function (a "callback") that will be invoked with the result when it arrives.

FWIW, if you were to use jQuery your entire code would just be:

function getIntervention(startdate, enddate) {
     return $.ajax({
         url: 'proxy.jsp', 
         data: {
             url: 'http://aqueduc.kelcode.com/proc/gw.php',
             requestName: 'getIntervention',
             uid: UID_GATEWAY,
             startDate: startdate,
             endDate: enddate
        });
};

getIntervention(a, b).done(function(jsondata) {
    // jsondata will be your data, already parsed
});

The only bit I've omitted is the settnig of the myDiv element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM