代码之家  ›  专栏  ›  技术社区  ›  4 Leave Cover

没有internet连接时,ajax会回退

  •  1
  • 4 Leave Cover  · 技术社区  · 7 年前

    以下代码将数据提交给服务器。在提交到服务器之前,数据实际上存储在本地存储中。这是因为我要求用户能够在没有互联网连接的情况下使用我的系统。

    问题是,当没有互联网连接时,它显然无法将数据发布到服务器。在这种情况下我该怎么办?

    $('#btnSync').on('click', function(e) {
        var my_data = {};
        var my_value = [];
    
        for ( var i = 0, len = localStorage.length; i < len; ++i ) {
            if((localStorage.key( i ).includes('set'))){
                var lsItems = JSON.parse(localStorage.getItem( localStorage.key( i ) ));
    
                allItems[localStorage.key( i )] = lsItems;
            }
        }
    
        $.ajax({
            url: "action.php",
            type: "POST",
            data: {'action':'btnSync','allItems':allItems},
            dataType: "json",
            success: function(data) {
                $.notify(
                    {
                        message: data.message
                    },
                    {
                        type: data.status,
                        placement: {
                            from: "top",
                            align: "left"
                        },
                        newest_on_top: true,
                        delay: 0
                    }
                );
            },
            error: function(data){
                $.notify(
                    {
                        message: 'Unexpected error occured, please kindly contact System Administrator'
                    },
                    {
                        type: 'danger',
                        placement: {
                            from: "top",
                            align: "left"
                        },
                        newest_on_top: true,
                        delay: 0
                    }
                );
            }
        });
    });
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Paun Narcis Iulian    7 年前

    您可以使用类似的ajax调用检查连接/服务器是否启动。寻找

    statusCode.status == 0
    

    错误,并向用户发出目的地无法到达/互联网关闭通知。您可以在函数中创建此ajax调用作为承诺,并在所有ajax调用之前使用它,然后要求用户连接到Internet,然后重试。