我一直在开发一个允许用户提交内容和内容的web应用程序,今天我看到了一些意想不到的结果,没有做任何重大的改变。
该应用程序的基本功能是用户从网页index.php
上的表单中提交一些POST数据,然后运行POST submit.php
将数据添加到数据库中的表中。同时,index.php
上的Jquery函数正在刷新div的内容,通过脚本load.php
从表中选择行,函数每秒调用一次。
问题是,今天,突然间,我看到数据被添加到表中时和在Jquery刷新的div中出现之间的延迟时间很长(10-20分钟)。此外,div在它现有的内容和新的数据集之间来回闪烁,好像它是在load.php
的实时结果和以前对同一个脚本的调用之间交替的。
在调用MySQL之前和之后,我已经检查了submit.php
数据库,并且验证了一旦提交数据就立即添加数据,所以问题与如何从Jquery调用load.php
脚本有关。
今天才开始。奇怪的是,我在前面构建的另一个AJAX应用程序中看到了同样的行为,这是为了测试相同的I/O机制,而且我已经一个多星期没有碰过那个应用程序的代码了。我的系统管理员说,服务器没有发生任何变化,这说明了这一点。
我已经发布了提供所有必要信息的所有代码,但我认为问题要么出现在load.php
中,要么出现在index.php
中的javascript updateMyContent()
中。
index.php
<script language="JavaScript">
setInterval("updateMyContent();",1000);
$(function(){
updateMyContent=function(){
$('#refreshData').load("./module/load.php").fadeIn("slow");
}
});
</script>
<script language="JavaScript">
$(document).ready(function(){
$('#submitForm').on('submit',function(e){
$.ajax({
url:'./module/submit.php',
data:$('#submitForm').serialize(),
type:'POST',
success:function(data){
console.log(data);
$("#success").show().fadeOut(5000);
$('#textID').val('');
},
error:function(data){
$("#error").show().fadeOut(5000);
}
});
e.preventDefault();
});
});
</script>
<div style="float: right;
top: 0;
" id="submitDiv">
<form id="submitForm" action="" method="post">
<textarea id="textID" type="text" name="content" rows=5></textarea>
<input type="submit" value="send" name="submit"/>
</form>
<br>
<span id="error" style="display: none; color:#F00">error</span>
<span id="success" style="display:none; color:#0C0">success</span>
</div>
<div style="float: center;" id="refreshData"></div>
submit.php
<?php
if(isset($_POST['content']))
{
$content=$_POST['content'];
$dsn="mysql:host=someserver.net;dbname=thisdb;charset=utf8";
$db=new PDO($dsn,'thisdb','password');
$insertSQL="insert into submission (content) values (?)";
$stmt=$db->prepare($insertSQL);
$stmt->execute(array($content));
}
else
{
echo "FAIL!";
}
?>
load.php
<?php
try
{
$dsn="mysql:host=someserver.net;dbname=thisdb;charset=utf8";
$db=new PDO($dsn,'thisdb','password');
$PDOsql="select * from submission order by id desc";
$stmt=$db->query($PDOsql);
foreach($stmt->fetchAll(PDO::FETCH_ASSOC) as $resultRow)
{
printf("%s<br>",$resultRow["ID"]);
printf("%s<br>",htmlspecialchars($resultRow["content"]));
$stmt->closeCursor();
}
}
catch(PDOException $ex)
{
echo "an error occurred! ".$ex->getMessage();
}
?>
发布于 2014-05-08 23:44:02
返回Ajax响应花了这么长时间的问题可能是表submissions
已经增长了。而不是每秒钟加载所有提交,只附加新提交到div。也就是说,跟踪最后收到的id并在查询中使用它,以便where子句受到限制。
此外,div在它现有的内容和新的数据集之间来回闪烁,好像它是在load.php的实时结果和以前对同一个脚本的调用之间交替的。
Ajax响应可以由浏览器缓存,就像其他任何东西一样。为了防止这种情况,你可以:
$.ajaxSetup ({ cache: false });
或将cache: false,
属性添加到$.ajax
的每个调用中https://stackoverflow.com/questions/23554354
复制相似问题