今天接触ajax,通过一个小小的例子来加深对ajax的了解
通过index.PHP的下拉框选择班级,然后通过ajax的post传值给result.PHP,result.PHP通过传过来的班级名
到数据库中查找相应班级里的学生,再把学生信息返回给index.PHP。
本例已通过测试
<?PHP //从数据库把班级名称取出来放入下拉列表中 MysqL_connect("localhost","root","root") or die("数据库连接失败"); MysqL_select_db("studentmanage") or die("数据库不存在"); $sql="select * from class"; $rs=MysqL_query($sql); $info=array(); while($row=MysqL_fetch_assoc($rs)){ $info[]=$row; } ?> <!doctype html> <html> <head> <title>查询学生信息</title> <Meta http-equiv="content-type" content="text/html;charset=utf-8"/> <style type="text/css"> #content{ margin:0 auto; width:600px; text-align:center; } h3{ background-color:black; color:#fff; } </style> <script type="text/javascript"> function getMessage(){ var xmlhttprequest; if(window.ActiveXObject){ try{ xmlhttprequest=new ActiveXObject("Microsoft.XMLHTTP"); }catch(e){ try{ xmlhttprequest=new ActiveXObject("Msxml2.XMLHTTP"); }catch(e){} } }else{ xmlhttprequest=new XMLHttpRequest(); } if(xmlhttprequest){ var url="result.PHP"; var cid=document.getElementById("class").value; //window.alert(cid); var show=document.getElementById("info"); //window.alert(show); var data="class="+cid; //window.alert(data); xmlhttprequest.open("post",url,true); xmlhttprequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //window.alert(url+data); xmlhttprequest.onreadystatechange=function(){ if(xmlhttprequest.readyState==4){ if(xmlhttprequest.status==200){ var info=xmlhttprequest.responseText; if(info==""){ show.innerHTML="你好,你查询的班级暂时还没有学生"; }else{ show.innerHTML=info; } } }else{ //window.alert("error"); } } xmlhttprequest.send(data); }else{ window.alert("不能创建xmlhttprequest对象"); } } </script> </head> <body> <div id="content"> <h3> 请选择班级: <select name="class" id="class" onchange="getMessage()"> <option value="" selected>choose class</option> <?PHP foreach($info as $v){?> <option value="<?PHP echo $v['cid'];?>"><?PHP echo $v['cname'];?></option> <?PHP }?> </select> </h3> <div id="info"></div> </div> </body> </html>
<?PHP //header("content-type:text/html;charset=utf-8"); header("Content-type:text/xml;charset=utf-8"); header("Cache-Control:no-cache"); $class=$_POST['class']; file_put_contents("D:/WWW/PHPDemo/log.log",$class."\r\n",FILE_APPEND); MysqL_connect("localhost","root") or die("数据库连接失败"); MysqL_select_db("studentmanage"); MysqL_query("set names utf-8"); $sql="select * from student where cid='$class'"; //$sql="select * from student where cid=3"; $rs=MysqL_query($sql); $info=array(); while($row=MysqL_fetch_assoc($rs)){ $info[]=$row; } $result="<table style='border:solid 1px;width:600px;'><tr><th>学号</th><th>姓名</th><th>住址</th><th>班级</th></tr>"; foreach($info as $v){ $result.="<tr><td>{$v['sid']}</td><td>{$v['name']}</td><td>{$v['address']}</td><td>{$v['cid']}</td></tr>"; } $result.="</table>"; file_put_contents("D:/WWW/PHPDemo/log.log",$result."\r\n",FILE_APPEND); echo $result; ?>
通过post传值要注意很多细节,否则很容易出错 原文链接:https://www.f2er.com/ajax/165023.html