我在下面函数里主要是向jsp发送了一个post,能够得到一个json的字符串,而且已经得到了正确的结果(测试过)。但是不能把得到的json对象,或是字符串return。
意思就是用别的函数调用这个函数,想得到传回来的值。但是得到的结果打印出来都是undefined。
例如 var data = getIntervention(date1,date2)
data的值就是undefined。
但是在onreadystatechange = function()中确实已取到正确的数据。
是不是用ajax发post得到结果后只能在onreadystatechange这个函数内处理,而不能回传?
有没有相似经历的人?或者做个类似的实验?
- 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("不能创建对象"); 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+""); }
------解决方案--------------------
状态函数中return 返回值没有意义,应该是getIntervention这个函数需要return。你的这个要求需要改成同步的
- 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("不能创建对象"); 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.open("POST","proxy.jsp",false);////////改成同步的 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+""); ////////////////////////////////// var jsondata=eval('('+xmlhttp.responseText+')'); document.getElementById("myDiv").innerHTML=jsondata.nbMissions; return jsondata; }