Ajax的GET传值没问题,POST传值有问题!!!帮忙看看!!!!
如果把这些代码改成GET方式就正常,而用POST方式时,在gethint.php里就获取不到post传来的数据,这是怎么回事?帮忙看看,谢谢!
共三个文件,如下:
1. text.php
<html><head><script src="clienthint.js"></script></head><body><form>First Name:<input type="text" id="txt1"><input type="button" value="Submit" onClick="showHint()"></form><p>Suggestions: <span id="txtHint"></span></p></body></html>
var xmlHttpfunction showHint(){var str = document.getElementById("txt1").value;if (str.length==0) { document.getElementById("txtHint").innerHTML=""; return; }xmlHttp=GetXmlHttpObject();if (xmlHttp==null) { alert ("Browser does not support HTTP Request"); return; }var url="gethint.php";var content="qt="+str;content=content+"&sid="+Math.random();xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//for postxmlHttp.onreadystatechange=stateChanged;xmlHttp.open("POST",url,true);xmlHttp.send(content);}function stateChanged(){if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") { document.getElementById("txtHint").innerHTML=xmlHttp.responseText; }}function GetXmlHttpObject(){var xmlHttp=null;try {// Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); }catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } }return xmlHttp;}<?php// Fill up array with names$a[]="Anna";$a[]="Brittany";$q = $_POST["qt"];if (strlen($q) > 0){$hint="";for($i=0; $i<count($a); $i++) { if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q)))) { if ($hint=="") { $hint=$a[$i]; } else { $hint=$hint." , ".$a[$i]; } } }}else echo "q is empty!<br>";//Set output to "no suggestion" if no hint were found//or to the correct valuesif ($hint == ""){$response="no suggestion";}else{$response=$hint;}//output the responseecho $response;echo " to ";echo $q;echo "<br>";?>
function stateChanged(){
alert(xmlHttp.readyState)
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
alert(xmlhttp.status)
if (xmlhttp.status==200||xmlhttp.status==0){
document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
}
}
}
你把alert结果贴上来,或自己根据提示找原因
[解决办法]
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//for post
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("POST",url,true);
setRequestHeader方法要在open后再调用,要不出错
//xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//for postxmlHttp.onreadystatechange=stateChanged;xmlHttp.open("POST",url,true);xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//for post========
[解决办法]