我有一个服务器并为其创建一个 Web 界面,如果用户按下页面上的重新启动按钮,则用户将被重定向到reboot.php
他应该看到一个旋转 gif,直到服务器再次可访问并且服务器通过 shell 执行重新启动。如果服务器可以访问,那么我需要重定向到main.php
所以我创建了以下函数。该函数以 5 秒的超时时间启动,否则它会立即加载main.php
因为重新启动命令需要时间。
重新启动.php
$ret = false;
test();
function test()
{
setTimeout
(
function()
{
$ret = ping("www.google.de");
if ($ret === false)
{
test();
}
else
{
window.location.href = "main.php";
}
},
3000
);
}
function ping(url)
{
$.ajax
(
{
url: url,
success: function(result)
{
alert('reply');
return true;
},
error: function(result)
{
alert('timeout/error');
return false;
}
}
);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-lg-6 col-lg-offset-3" id="mydiv">
<div class="mydiv_inhalt">
<h2>Rebooting...</h2>
<p>This can take about 2 minutes.</p>
<center>
<div class="waiting" id="waiting" style="margin-top:30px; margin-left: 0px;">
<center><img class="loading_table" src="http://www.securenet.com/sites/default/files/spinner.gif" alt="spinner gif"></center>
</div>
</center>
</div>
</div>
ajax.php
$cmd = filter_input(INPUT_POST, "cmd");
if ( isset( $cmd ) && $cmd == "check_online_status" )
{
echo "true";
}
In my ajax.php
如果调用成功,我只是返回“true”。
然而,我的逻辑不起作用,似乎我的代码只尝试对我的ajax.php
然后再也没有尝试过,我得到了net::ERR_CONNECTION_REFUSED
在控制台中。
我在代码中放入了很多警报,但它们没有执行,所以我猜它不会尝试调用ajax.php
获得后第二次net::ERR_CONNECTION_REFUSED
.
我唯一的想法是等待足够的时间,然后重定向到main.php
,但这不是一个好的解决方案,因为需要运气,如果时间不够怎么办等等。
让我们总结一下代码中的问题:
- 你需要使用
setInterval
每 x 秒执行一次该函数
- ajax 请求是异步的,它应该保持这样。您不能期望回调返回值,相反,您应该采取行动in回调
结果代码更简单:
var pingUrl = "www.google.de";
var targetUrl = "main.php";
setInterval(ping, 3000);
function ping() {
$.ajax({
url: pingUrl,
success: function(result) {
window.location.href = targetUrl;
}
});
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)