如果连接丢失,javascript不会重新连接到服务器端

时间:2012-03-06 08:00:14

标签: javascript jquery ajax

我有连接到服务器的Jquery + Ajax页面获取一些数据并显示它。这是在所有时间完成的,函数在完成所有任务后自行调用并开始反复执行。但如果komputer失去互联网连接,一切都会停止。当连接再次出现时,没有任何反应。这是javascript代码。如何进行iprove,以便在连接重新开始后它将继续工作。

$(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&nbsp;');
            $('#div_price_after').html('&nbsp;Euro');

                $('#main').fadeIn(2000).delay(3000).fadeOut(2000, function() 
                    {

                            $('#main').hide;
                            a++;
                            kiosk();


                    });

        });
    }
    else
    {
        a=1;
        kiosk();
    }

}
kiosk();
});

3 个答案:

答案 0 :(得分:3)

我建议使用

而不是使用$ .post

$ .ajax({type:“post”,success:function1(),failure:function2()}。

在function2()中,您可以在超时后再次调用koisk。并且succces将是你现在创建的功能。

此链接将帮助您了解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&nbsp;');
        $('#div_price_after').html('&nbsp;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();
}

} 亭(); });`

答案 1 :(得分:0)

使用jQuery.post传递回调,该回调仅在成功时执行。 您应该使用具有不同回调的jQuery.ajax。通过completesuccesserror回调,查看documentation

您甚至可以使用statusCode将特定HTTP代码映射到自定义函数。

答案 2 :(得分:-1)

脚本破坏因为我认为它会抛出异常。您可以添加代码try和catch块,即使有错误,您也可以继续尝试。

try {
    result = jQuery.parseJSON(result);
    // do your work
} catch {
    // call function again
}

或者你可以使用,jquery ajax,它有一个onerror事件。

相关问题