简体   繁体   English

AJAX发送发布请求,不能将值返回给其他函数吗?

[英]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. 我想从onreadystatechange = function(){}返回一个json对象,但是失败了。 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? 例如,当我调用函数getIntervention(startdate,enddate)时,“ onreadystatechange = function(){}”中的json数据将返回哪里?

[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: FWIW,如果您使用jQuery,则整个代码将是:

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. 我唯一省略的是myDiv元素的myDiv

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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