繁体   English   中英

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

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

我想从onreadystatechange = function(){}返回一个json对象,但是失败了。 您能给我一种方法吗? 例如,当我调用函数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+"");
}

您根本无法从异步方法返回结果。

您唯一可以做的就是将另一个函数(“回调”)排队, 函数将在到达时随结果一起调用。

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
});

我唯一省略的是myDiv元素的myDiv

暂无
暂无

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

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