我在我的网站上使用 jQuery + PHP,我想做这样的事情:
为了简化事情,我有一个带有 2 个按钮 () 的页面,根据我的点击,我想在后台启动一个脚本(php 脚本),所以我用 jquery 做了一个简单的事情:
$("#button1").click(function(){
$.post("script.php", {val:"but1"}, function(result){
alert(result); // I want something with the result
});
});
$("#button2").click(function(){
$.post("script.php", {val:"but2"}, function(result){
alert(result);
});
});
在 script.php 中,我有一个简单的 if 语句来决定我应该做什么。
在 php 脚本中,我正在下载一个文件,我想创建一个文件下载的进度条。 PHP 脚本会在某个时间间隔内返回值(echo百分比;flush();
)。
问题来了 - 当我回显这些百分比值并刷新它时,它会“仅在 php 中”刷新它,但 jquery 会一直等到脚本完成。有没有办法在这些值出现时(刷新后)获取它们,或者是否有完全其他的方法?我现在想不出其他什么,也许我根本不应该使用jquery。
感谢您的帮助。
最佳答案
您可以在运行脚本时将进度存储在文本文件或数据库中,然后让另一个文件通过 AJAX 调用获取结果。
JS/HTML
<script>
$(function() {
var id;
var timeoutLength = 1000;
$("#button1").click(function() {
$("#result").html("");
// Create unique identifier
id = (new Date().getTime()) + "-" + Math.floor(Math.random()*100);
$.get("script.php", {id: id}, function(result){
$("#result").html(result);
});
setTimeout(checkProgress, timeoutLength);
});
function checkProgress() {
$.get("script.php", {progress: true, id: id}, function(data) {
prog = parseInt(data);
// Display progress bar
if(prog < 100) {
$("#progress").css({ display: 'block', width: prog });
$("#progress").html(prog + "%");
setTimeout(checkProgress, timeoutLength);
} else {
$("#progress").css('display', 'none');
}
});
}
})
</script>
<button id="button1">Click</button>
<div id="progress" style="background: green"></div>
<div id="result"></div>
脚本.php
<?php
function getProgress($file) {
return (file_exists($file)) ? file_get_contents($file) : 0;
}
function setProgress($file, $progress) {
file_put_contents($file, $progress);
}
// Remove invalid characters
$id = str_replace('/[^a-zA-Z0-9\-_]/', '', $_GET['id']);
$file = "progress-" . $id . ".txt";
if(isset($_GET['progress'])) {
echo getProgress($file);
} else {
// Do something and update progress
for($i = 10; $i <= 100; $i += 10) {
// Do something
setProgress($file, $i);
sleep(1);
}
unlink($file);
echo "Result: " . rand(1, 100);
}
编辑: 添加了对多个请求和简单进度条的支持。
关于PHP + jQuery 同步问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6369315/