首先新建一个文件我给它取名字为index.php文件
代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>ajax的get请求练习</title> </head> <body> <form id="searchform" name="searchform" method="get" action="#"> <tr> <td align="center">请输入关键字: <input name="searchtxt" type="text" id="searchtxt" size="30"/> <br/> <input id="s_search" name="s_search" type="button" value="查询" onclick="showSimple()"/> </td> </tr> </form> <script type="text/javascript"> /** * 初始化xmlHttpRequest对象 * @returns {*} */ var xmlHttpReuest; function initXmlHttpRequest() { //定义xmlHttpRequest变量 try { if(window.ActiveXObject){ //老版本的兼容 xmlHttpReuest=new ActiveObject("Microsoft.XMLHTTP"); }else{ xmlHttpReuest=new XMLHttpRequest(); } }catch (e){ xmlHttpReuest=false; }finally { //做判断 if (!xmlHttpReuest){ alert("xmlHttpRequest实例化失败"); }else{ return xmlHttpReuest; } } } /** * 显示简单的例子 */ function showSimple() { //拿到 initXmlHttpRequest(); var cont=document.getElementById("searchtxt").value; // document.write("输出"+cont); if(cont==""){ alert("你输入的关键字不能为空"); return false; } //检查xml xmlHttpReuest.onreadystatechange=stateHandler; //打开 xmlHttpReuest.open('GET','searchrst.php?cont='+cont,true);//你要打开后台的哪个文件 以及以什么样的方式打开 xmlHttpReuest.send(null); } /** * 状态更新 */ function stateHandler() { //document.write("输出"+xmlHttpReuest.readyState); if(xmlHttpReuest.readyState==4&&xmlHttpReuest.status==200){ alert("弹出对话框了"); document.getElementById("webpage").innerHTML=xmlHttpReuest.responseText; }else{ // if (xmlHttpReuest.readyState==0){ // document.write("readyState="+xmlHttpReuest.readyState); // }else if (xmlHttpReuest.readyState==1){ // document.write("readyState="+xmlHttpReuest.readyState); // }else if (xmlHttpReuest.readyState==2){ // document.write("readyState="+xmlHttpReuest.readyState); // } } } </script> <tr> <td align="center" valign="top"><div id="webpage"></div></td> </tr> </body> </html>
//然后我们看看后台文件searchrst.php的代码
<?php header("content-type:text/html;charset=utf-8"); include_once 'index1.php';//这行代码去掉就不会有2个表单显示出来了 //接收cont $cont=$_GET['cont']; if (!empty($cont)){ //逻辑代码 echo $cont; }
//运行效果如下