更改SESSION变量以停止&"while循环&". [英] Change SESSION variable to stop "while loop"
问题描述
我是php的新手,我想使用按钮(启动/停止)控制php while循环脚本,启动按钮对定义了 start.php 脚本的ajax调用 $ _ SESSION ['loop'] = TRUE
并执行循环,停止按钮对 stop.php 脚本进行ajax调用,只需更改 $ _ SESSION ['loop']
更改为 FALSE
.
I'm new to php and I want to control a php while loop script, using buttons (start/stop), the start button make an ajax call to the start.php script that define $_SESSION['loop'] = TRUE
and execute the loop, the stop button make an ajax call to the stop.php script that just change $_SESSION['loop']
to FALSE
.
到目前为止,下面是我的代码,但是当我按下停止"按钮时,只有在while循环完成循环之后,我才发出警报(成功停止),这意味着循环没有像我一样中断是在假设.
Below is my code so far, but when I hit the stop button I became the alert (success stop) only after the while loop finish looping, which mean the loop didn't break as I was assuming.
我认为这与会话在执行循环时被锁定有关.如果是这样,如何更改 $ _ SESSION ['loop']
值并使循环每个时间读取该值?
I think it's something with the session that is locked while the loop is executing. If so, how to change the $_SESSION['loop']
value and make the loop read that value each time?
index.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#start').click(function(){
$.ajax({
url: "start.php"
});
});
$('#stop').click(function(){
$.ajax({
url: "stop.php",
success: function(){
alert('success stop');
},
error: function(){
alert('failure stop');
}
});
});
});
</script>
<button id="start">Start</button>
<button id="stop">Stop</button>
start.php
<?php
session_start();
$_SESSION['loop'] = TRUE;
ini_set('max_execution_time', 300);
$i = 0;
while($i < 100) {
if ($_SESSION['loop'] == TRUE) {
//query to save some variables
// Pause 10s after saving 2
if ($i != 0 && $i%2 == 0) {
sleep(10);
}
$i++;
} else {
break;
}
}
?>
stop.php
<?php
session_start();
if(isset($_SESSION['loop'])) {
$_SESSION['loop'] = FALSE;
}
?>
推荐答案
您的启动和停止操作处于两个不同的会话中,因此在一个会话中更改$ SESSION不会对另一个会话造成任何影响.
Your start and stop operations are in two different sessions, so changing $SESSION in one makes no difference to the other.
这篇关于更改SESSION变量以停止&"while循环&".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!