我有 Jquery+Ajax 页面,连接到服务器获取一些数据,并显示它。这是一直在完成的,函数在完成所有任务后调用自身并开始一次又一次地执行。但如果计算机失去互联网连接,一切都会停止。当连接再次恢复时,什么也没有发生。这是 JavaScript 代码。我怎样才能证明它,以便在连接再次恢复后它仍能继续工作。
$(document).ready(function() {
var a=1;
var max='23';
function kiosk()
{
if(a<max)
{
$.post('engine.php', { index: a },
function(result)
{
result = jQuery.parseJSON(result);
$('#main').css({'display':'none'});
$('#div_city').html(result.dest);
$('#div_price').html(result.price);
$('#div_price_pre').html('From ');
$('#div_price_after').html(' Euro');
$('#main').fadeIn(2000).delay(3000).fadeOut(2000, function()
{
$('#main').hide;
a++;
kiosk();
});
});
}
else
{
a=1;
kiosk();
}
}
kiosk();
});
最佳答案
我建议您不要使用 $.post
$.ajax({ 类型: "post", 成功: function1() , 失败: function2() }.
在 function2() 中,您可以在超时后再次调用 koisk。成功将是您现在创建的函数。
此链接将帮助您了解ajax功能jQuery Ajax error handling, show custom exception messages
例如代码片段:
function kiosk()
{
if(a<max)
{
$.ajax({type : "POST" , url : 'engine.php',data: { index: a },
success : function(result)
{
result = jQuery.parseJSON(result);
$('#main').css({'display':'none'});
$('#div_city').html(result.dest);
$('#div_price').html(result.price);
$('#div_price_pre').html('From ');
$('#div_price_after').html(' Euro');
$('#main').fadeIn(2000).delay(3000).fadeOut(2000, function()
{
$('#main').hide;
a++;
kiosk();
});
},error : function (xhr, ajaxOptions, thrownError){ setTimeout(200,kiosk()) }
});
}
else
{
a=1;
kiosk();
}
} 亭(); });`
关于如果连接丢失,javascript不会重新连接到服务器端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9579869/