这里不仅有一个问题
您的问题将是两个:
- 如何在PHP中对特定函数进行AJAX调用?
- 如何使用AJAX制作进度条?
如何在PHP中对特定函数进行AJAX调用?
您的AJAX代码很好。您在PHP中唯一要做的就是接收此调用。
看看你的要求。您
nr随请求发送一个变量:
server_side.php?nr="+loop_index
这将帮助我们在php代码中确定这是进行求和操作的AJAX调用。现在在PHP中:
<?php session_start();//We look at the GET php variable to see if the "nr" is comingif(isset($_GET['nr'])) { //Its coming!. Now we procede to call our function to sum $result = sum($_GET['nr']);}function sum($nr) { $progress = 0 ; $sum = 0 ; for ($i = 1; $i <= $nr; $i++) { $sum = $sum + $i; $progress++; $_SESSION['progress'] = $progress; } echo $sum;}而已。
如何使用AJAX制作进度条?
我们需要进行其他AJAX调用以请求PHP的进度。
首先,我们进行另一个AJAX调用,以使用计时器检索进度!
var timer; //try to delete duplications. Do a generic function that does the request to php function makeRequest(toPHP, callback) { var xmlhttp; if (window.XMLHttpRequest) {// pre for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// pre for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { callback(xmlhttp.response); } } xmlhttp.open("GET",toPHP,true); xmlhttp.send(); } function loop() { var loop_index = document.getElementById("loop_nr").value; makeRequest("server_side.php?nr="+loop_index, function(response) { document.getElementById("sumDiv").innerHTML="Total sum = " + response; clearInterval(timer); }); timer=setInterval(makeRequest("getter.php", function(response) { document.getElementById("percentageDiv").innerHTML=response; }),1000); }然后在php端,我们像以前一样检索此调用,并回显
$_SESSION['progress'](就像您已经拥有的)
<?php session_start(); $progress = $_SESSION['progress']; echo $progress;?>
就是这样!



