我想为服务器端任务(使用PHP编写)创建一个进度条。
为了学习目的,示例和任务非常简单。我将在客户端页面上有一个文本字段,读取一个数字,通过ajax将其传递给php脚本,并让它计算所有数字的总和,从0到数字(一个简单的任务,对于大数字需要一些时间,只是模拟一些服务器端工作)。
在.html文件中,我将创建一个定时器,每n秒调用一个函数,获取我的for循环的索引并更新进度条。
我的问题是:
在同一个php文件中是否可能有两个函数,以及如何使用ajax调用特定函数:一个函数将阻止循环到数字,另一个函数将调用以获取当前索引。
我目前拥有的代码:
感谢您!
为了学习目的,示例和任务非常简单。我将在客户端页面上有一个文本字段,读取一个数字,通过ajax将其传递给php脚本,并让它计算所有数字的总和,从0到数字(一个简单的任务,对于大数字需要一些时间,只是模拟一些服务器端工作)。
在.html文件中,我将创建一个定时器,每n秒调用一个函数,获取我的for循环的索引并更新进度条。
我的问题是:
在同一个php文件中是否可能有两个函数,以及如何使用ajax调用特定函数:一个函数将阻止循环到数字,另一个函数将调用以获取当前索引。
我目前拥有的代码:
<!DOCTYPE html>
<html>
<head>
<script>
function myTimer()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("percentageDiv").innerHTML=xmlhttp.response;
alert(xmlhttp.response);
}
}
xmlhttp.open("GET","getter.php",true);
xmlhttp.send();
}
function loop(){
var loop_index = document.getElementById("loop_nr").value;
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("sumDiv").innerHTML="Total sum = " + xmlhttp.response;
clearInterval(myVar);
}
}
xmlhttp.open("GET","server_side.php?nr="+loop_index,true);
xmlhttp.send();
var myVar=setInterval(function(){myTimer()},1000);
}
</script>
</head>
<body>
<div id="percentageDiv"> Percentage div</div>
<div id="sumDiv"></div>
<input type="text" id="loop_nr">
<input type="submit" onclick="loop()">
</body>
</html>
server_side.php
<?php
session_start();
$index=$_GET["nr"];
$progress = 0 ;
$sum = 0 ;
for ($i = 1; $i <= $index; $i++) {
$sum = $sum + $i;
$progress++;
$_SESSION['progress'] = $progress;
}
echo $sum;
?>
getter.php
<?php
session_start();
$progress = $_SESSION['progress'];
echo $progress;
?>
感谢您!
$_SESSION
中以便持久化。 - Tomás