日期:2014-05-16  浏览次数:20687 次

初学者求助:使用AJAX刷新的内容一闪就消失了
初学者,想做一个页面,点击按钮,向服务器端PHP文件发出指令,服务器端根据指令不同,查询数据库,将不同内容返回到页面,通过AJAX在页面下方刷新出来。
之前都很顺,但是到了刷新的时候,就出问题了。
首先,需要的内容确实刷新出来了,但只存在了一瞬间,一闪而过,然后页面又还原到点击之前的效果。。我试了很多方法,最后在刷新后加了句alert才把页面定住,看见了效果。。
具体形容:页面下方空白,点击,出现内容(存在极短一段时间,约0.1~0.2S),内容消失,恢复点击前的空白
上面是第一个问题
第二个问题,在发送xmlHttp.send()下面,我只有在加了一个alert拖延几秒之后,才能接收到服务器的响应,如果不加就会“跑飞了”,但如果这个alert放着不点,过了几秒接收到的响应就有错误或者收不到。
下面是我的部分页面代码
<script type="text/javascript">
function require(str)
{
var xmlHttp;
xmlHttp=null;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlHttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
var url="read.php";
xmlHttp.onreadystatechange=function()
  {
  if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
    {
//    document.getElementById("liebiao").innerHTML=xmlHttp.responseText;
var response;
response = xmlHttp.responseText;
alert(response);
document.getElementById("liebiao").innerHTML=response;
// alert(response);//这就是我用来定住页面的alert。。
return
    }
  }
xmlHttp.open("POST",url,true);
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded;charset=utf-8");
xmlHttp.setRequestHeader("If-Modified-Since","0");
xmlHttp.send("&require=" + str);
alert("正在加载,请稍候");//这一句似乎能用来占位,注释掉以后,程序像是跑飞了。。

</script>

<form>
<input id="all" name="all" type="submit" value="全部留言" onclick="require(this.value)"/>
<input id="have" name="have" type="submit" value="已处理" onclick="require(this.value)"/>
<input id="havent" name="havent" type="submit" value="未处理" onclick="require(this.value)"/>
</form>

下面是服务器端部分PHP代码
<?php
$con = mysql_connect("localhost","root","cyx1991430");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("my_db", $con);
if($_POST["require"]=="全部留言")
{
$result = mysql_query("SELECT * FROM liuyan");
echo "<table style='width:400px' border='1'>
<tr>
<th>留言者</th>
<th>留言时间</th>
<th>联系邮箱</th>
<th>留言状态</th>
<th>查看详情</th>
</tr>";
while($row = mysql_fetch_array($result))