Rumah > Artikel > pembangunan bahagian belakang > 通过ajax POST传值,但返回为空解决思路
通过ajax POST传值,但返回为空
第一次接触ajax,想通过一个简单的例子来练练
index.php中有一个下拉列表,选择不同的班级返回不同的学生信息
代码如下:
<?php<br /> //从数据库把班级名称取出来放入下拉列表中<br /> mysql_connect("localhost","root","root") or die("数据库连接失败");<br /> mysql_select_db("studentmanage") or die("数据库不存在");<br /> <br /> $sql="select * from class";<br /> $rs=mysql_query($sql);<br /> $info=array();<br /> while($row=mysql_fetch_assoc($rs)){<br /> $info[]=$row;<br /> }<br /><br />?><br /><!doctype html><br /><html><br /> <head><br /> <title>查询学生信息</title><br /> <meta http-equiv="content-type" content="text/html;charset=utf-8"/><br /> <style type="text/css"><br /> <br /> </style><br /> <script type="text/javascript"><br /> var xmlhttprequest;;<br /> function getMessage(){<br /> <br /> if(window.ActiveXObject){<br /> xmlhttprequest=new ActiveXObject("Microsoft.XMLHTTP");<br /> }else{<br /> xmlhttprequest=new XMLHttpRequest();<br /> }<br /> <br /> if(xmlhttprequest){<br /> var url="result.php";<br /> var cid=document.getElementById("class").value;<br /> var show=document.getElementById("info");<br /> var data="class=cid";<br /> xmlhttprequest.open("post",url,true);<br /> xmlhttprequest.setRequestHeader("content-type","application/x-www-form-urlencode");<br /> xmlhttprequest.onreadystatechange=function(){<br /> if(xmlhttprequest.readyState==4){<br /> if(xmlhttprequest.status==200){<br /> var info=xmlhttprequest.responseText;<br /> if(info==""){<br /> show.value="你好,你查询的班级暂时还没有学生";<br /> }else{<br /> show.value=info;<br /> }<br /> }<br /> }else{<br /> alert("error");<br /> }<br /> }<br /> xmlhttprequest.send(data);<br /> }<br /> }<br /> </script><br /> </head><br /> <body><br /> <div id="content"><br /> <h1><br /> 请选择班级:<br /> <select name="class" id="class" onchange="getMessage()"><br /> <option value="" selected>choose class</option><br /> <?php foreach($info as $v){?><br /> <option value="<?php echo $v['cid'];?>"><?php echo $v['cname'];?></option><br /> <?php }?><br /> </select><br /> </h1><br /> <div id="info"></div><br /> </div><br /> </body><br /></html>
<?php<br /> //header("content-type:text/html;charset=utf-8");<br /> header("Content-type:text/xml;charset=utf-8");<br /> header("Cache-Control:no-cache");<br /> $class=$_POST['class'];<br /> <br /> mysql_connect("localhost","root","root") or die("数据库连接失败");<br /> mysql_select_db("studentmanage");<br /> mysql_query("set names utf-8");<br /> $sql="select * from student where cid='$class'";<br /> //$sql="select * from student where cid=3";<br /> $rs=mysql_query($sql);<br /> $info=array();<br /> while($row=mysql_fetch_assoc($rs)){<br /> $info[]=$row;<br /> }<br /> <br /> $result="<table><tr><td>学号</td><td>姓名</td><td>住址</td><td>班级</td></tr>";<br /> foreach($info as $v){<br /> $result.="<tr><td>{$v['sid']}</td><td>{$v['name']}</td><td>{$v['address']}</td><td>{$v['cid']}</td></tr>";<br /> }<br /> $result.="</table>";<br /> echo $result;<br />?>