最近正在学PHP,正好学习到AJAX与PHP的交互,特此记录一下,以便以后参考。
1、创建XMLHttpRequest对象
1 function GetXmlHttpObject(){ 2 var XmlHttp=null; 3 try{ 4 XmlHttp=new XMLHttpRequest(); 5 } 6 catch(e){ 7 try{ 8 XmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); 9 } 10 catch(e){ 11 XmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); 12 } 13 }; 14 return XmlHttp; 15 }
2、请求XMLHttpRequest对象
<input type="button" onclick="testRequest()"><br/> <div id="getReturnStr" style="border:solid 1px;width:500px;height:400px;"></div>
var xmlHttp; function testRequest(){ xmlHttp=GetXmlHttpObject(); if(xmlHttp==null){ alert ("Browser does not support HTTP Request"); return; } var url="test.php?&id="+Math.random(); xmlHttp.onreadystatechange=statechange; xmlHttp.open("get",url,true); xmlHttp.send(null); } function statechange(){ if(xmlHttp.readyState==4||xmlHttp.readyState=="Complete") { document.getElementById("getReturnStr").innerText=xmlHttp.responseText; } }
3、写请求页面test.PHP
<?php $requestStr=$_REQUEST["id"]; echo $requestStr; ?>