raw*_*ors 5 php ajax jquery polling
我想定期检查php脚本的状态并在浏览器上显示它.这是用于发布的jQuery.
$(document).ready(function() {
$("#tempbut").click(function(event){
$('#loader').show();
$('#mainarea').hide('fast');
$.post(
"template.php",
{
guide : $('#guide').val(),
title : $('#title').val()
},
function(data) {
$('#mainarea').empty();
$('#loader').fadeOut('slow');
$('#mainarea').append(data);
$('#mainarea').show('slow');
}
);
});
});
Run Code Online (Sandbox Code Playgroud)
在PHP脚本(未发布)中,我回显诸如"构建请求...","发送请求..."之类的语句,以通知用户进度.如果我没有使用jQuery post,我可以在每个echo之后使用flush()和obflush()显示状态.也许是因为回调在输出之前等待脚本完全执行?
有没有办法修改现有的jQuery .post来做到这一点?我看到一些使用.ajax的例子,但不是.post.
如果.ajax是唯一的方法,我将如何修改此代码?
谢谢!
编辑: 运行了!希望有人会觉得这很有帮助.(你可以删除console.log)
的test.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>TEST</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge;chrome=1" />
<script src="http://code.jquery.com/jquery-2.1.0.js"></script>
<script>
$.ajax({
url: "test.php",
xhrFields: {
onprogress: function(e) {
console.log(e.target.responseText)
$("body").html(e.target.responseText)
if (e.lengthComputable) {
console.log(e.loaded / e.total * 100 + '%');
}
}
},
success: function(text) {
console.log(text)
$("body").html(text+"<h1>done!</h1>")
}
});
</script>
</head>
<body>
<div id="derp">TEST!</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
test.php的
<?php
for($i = 0; $i<20 ; $i++){
sleep(1);
echo $i."</br>";
flush();
ob_flush();
}
?>
Run Code Online (Sandbox Code Playgroud)
post 是 ajax(type:post) 的快捷方式,没有什么不同。
要获取进度报告,有一些方法。现在我的最简单的方法是向同一页面发出 2 个 ajax 请求 1 来运行 php 脚本并将状态存储在会话中,另一个发送到读取状态的不同页面来自会话并为用户打印它。
更新:
哦哦,直到 php 脚本完成之后,我的糟糕会话才被记录下来。您可以尝试将状态写入文件并从中读取,如下所示:
任务.php
for ($i = 0; $i < 10; $i++) {
echo($i . "<br/>");
file_put_contents('progress', $i);
sleep(2);
}
Run Code Online (Sandbox Code Playgroud)
进度.php
if (file_exists('progress') && is_readable('progress'))
echo file_get_contents('progress');
else
echo(-1);
Run Code Online (Sandbox Code Playgroud)
和脚本:
<script>
$(document).ready(function () {
task();
getProgress();
});
function task() {
$.ajax({
url: 'http://localhost/test/progress/task.php',
success: function (data) {
console.log('Task is over :' + data);
}
});
}
function getProgress() {
$.ajax({
url: 'http://localhost/test/progress/progress.php',
success: function (data) {
data = parseInt(data);
if (data != 9) {
console.log('progress :' + data);
setTimeout(function () {
getProgress();
}, 1000);
}
}
});
}
</script>
Run Code Online (Sandbox Code Playgroud)
但是在多用户环境中这会导致问题。
因此,您能做的最好的事情是将状态存储在其中之一中:
| 归档时间: |
|
| 查看次数: |
2809 次 |
| 最近记录: |