须要两个PHP页面:1.php是发出请求和接受请求结果的。2.php是处理请求的结果。javascript
1.php中代码:php
<a href="#" onclick="sendAjaxRequest();"></a>要有能触发JS中函数的标签,这里是a标签。在1.php页面中有JS代码进行请求:
var http_request=false; function sendAjaxRequest(){ //alert('进入执行SEND'); //执行前先进行清理上次的结果操做 SetHidden();//这里模拟各类对页面的操做 if(window.XMLHttpRequest)//请求对象是JavaScript中的对象XMLHttpRequest。 { http_request=new XMLHttpRequest(); }else if(window.ActiveXObject){ try { http_request=new ActiveXObject("Msxml2.XMLHTTP");//IE }catch (e){ try{ http_request=new ActiveXObject("Microsoft.XMLHTTP");//ForeFox }catch(e){} } } if(http_request) { http_request.open("POST","2.php",true);//指定请求处理页和请求方式及是否是异步 http_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');//设置请求头,应该还能设置其余请求头部信息 var postdata="keyword="+encodeURI(document.getElementById("keyword").value);//POST的数据,若是是GET方法就不用这里了 http_request.onreadystatechange = updatePage;//页面2.php交互请求时,指定函数updatePage来处理页面2.php的响应,有5种响应,因此要进行选择处理 http_request.send(postdata);//发送POST数据 } } function updatePage(){//此函数根据2.php所作的反应,来对页面1.php做出一些动做 if(http_request.readyState==4)//有5种响应0--4,最后一种4是处理完请求 { //alert('响应已完成,能够访问服务器响应并使用它'); //alert(http_request.responseText); var div=document.getElementById("divresult"); if(http_request.responseText.split(';')[0]!=""&&http_request.responseText.split(';')[0]!=undefined&&http_request.responseText.split(';')[1]!=undefined) { document.getElementById("label3").innerHTML=http_request.responseText.split(';')[0]+" "; document.getElementById("label5").innerHTML=http_request.responseText.split(';')[1]+" ";//这里responseText,是页面2.php echo函数打印的全部数据 div.style.display="block"; } else { alert("2.php处理完了"); } } } function SetHidden(){ document.getElementById("divresult").style.display="none"; }2.php中的响应:
<?php //作出的响应页面, $link=mysql_connect("192.168.100.100","ccc","ccc"); if($link) { $db_select=mysql_select_db("search",$link); mysql_query("set names utf8"); } if($db_select) { $result=mysql_query("select proname,person from search where APPKEY='".$_POST[keyword]."'",$link); mysql_close($link); } if($result) { $info=mysql_fetch_array($result); mysql_free_result($result); } if($info) { echo $info[proname];//最主要是输出的内容,是与1.php进行交互的基础,另外一种交互的方法是用GET和POST请求对1.php再次发出,1.php进行接收请求 echo ";".$info[1]; } ?>