簡體   English   中英

如果連接丟失,javascript不會重新連接到服務器端

[英]javascript does not reconnect to server side if connection is lost

我有連接到服務器的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();
});

我建議而不是使用你使用的$ .post

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

在function2()中,您可以在超時后再次調用koisk。 並且succces將是您現在創建的功能。

此鏈接將幫助您了解ajax函數jQuery Ajax錯誤處理,顯示自定義異常消息

例如代碼片段:

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();
}

} kiosk(); });`

使用jQuery.post傳遞一個僅在成功時執行的回調。 你應該使用具有不同回調的jQuery.ajax 請參閱包含completesuccesserror回調的文檔

您甚至可以使用statusCode將特定的HTTP代碼映射到自定義函數。

腳本破壞因為我認為它會拋出異常。 您可以添加代碼try和catch塊,即使有錯誤,您也可以繼續嘗試。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM