First create a new file and I name it index.php file
code show as below:
<!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"> /** * Initialize xmlHttpRequest object * @returns {*} */ var xmlHttpReuest ; function initXmlHttpRequest () { //Define xmlHttpRequest variable try { if ( window . ActiveXObject ){ //Compatible with old version xmlHttpReuest = new ActiveObject( "Microsoft .XMLHTTP" ); }else{ xmlHttpReuest=new XMLHttpRequest(); } }catch (e){ xmlHttpReuest=false; }finally { //Do judgment if (! xmlHttpReuest ){ alert ( "xmlHttpRequest instantiation failed" ); }else{ return xmlHttpReuest; } } } /** * show simple example */ function showSimple () { // get initXmlHttpRequest (); var cont = document . getElementById ( "searchtxt" ). value ; // document. write("output"+cont); if ( cont == "" ){ alert ( "The keyword you entered cannot be empty" ); return false ; } //check xml xmlHttpReuest .onreadystatechange = stateHandler ; // open xmlHttpReuest .open (' GET ' , 'searchrst.php?cont=' + cont , true );//Which file in the background do you want to open and in what way open xmlHttpReuest.send ( null ); _ } /** * status update */ function stateHandler () { //document.write("output"+xmlHttpReuest.readyState); if ( xmlHttpReuest . readyState == 4 && xmlHttpReuest . status == 200 ){ alert ( "Pop up dialog box" ); 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; }
//运行效果如下