jQuery mobile ajax检测设备是否没有互联网连接

时间:2014-02-08 11:54:14

标签: android ajax jquery-mobile cordova

我正在开发一个需要检测互联网连接的Android应用程序,如果该设备没有互联网连接,则会发出设备没有互联网连接的警报。

这是我的代码:

<script>
        var lform = $("#loginform");

        function verifyfirst(){
        if($( "#txtusername" ).val() == "" || $( "#txtpassword" ).val() == "")
        {
        return;
        }
        else
        {
        $.mobile.loading("show");

            $.getJSON("http://url/verifyfirst.php?callback=?", lform.serialize(),function(data)
            {
                if (data.verified == "v1")
                {
                localStorage.setItem("datausername", data.txtusername);

                    if (localStorage.getItem("datausername") == "admin")
                    {
                    location.href="admin.html";
                    }
                    else
                    {
                    //$.mobile.changePage( "menu.html", { changeHash: true });
                    location.href="menu.html";
                    }
                }
                else
                {
                $("#popuptext").html("<b>The account you've entered is not associated with Happy Au Pair. Please check your username or password.</b>");    
                $( "#popupAfter" ).popup( "open", { 
                positionTo: "window",
                transition: "pop" });
                $.mobile.loading("hide");
                }
            }).fail(function(data){

                $("#popuptext").html("<b>There is a problem with your login, please try again later.</b>");

                    $( "#popupAfter" ).popup( "open", { 
                    positionTo: "window",
                    transition: "pop"});
                    $.mobile.loading("hide");

            });
        }
        }
    </script>

我尝试将它组合在一起,但它不起作用:

<script>
    var online = navigator.onLine;
    if(online) {
     //I placed the ajax here
    } else {
       alert("Internet Connectivity is not available.");
    }
</script>

请帮助我实现这一目标。我正在使用build.phonegap.com导出apk文件。 提前谢谢。

2 个答案:

答案 0 :(得分:2)

 var condition = navigator.onLine ? "ONLINE" : "OFFLINE";

您将在线或离线,并可以相应地使用它。你也可以通过ajax调用来测试它

$.ajax({
    url: url,
    type: 'GET',
    contentType: "application/json;charset=utf-8",
    success: function (data) {
        // Yor success logic       
    },
    error: function (request) {
       // alert(request.responseText);
       // alert(request.status);
        if(request.status==0)
        {
           alert("Please connect to the internet");
        }

    }
});

答案 1 :(得分:1)

尝试在发送实际请求之前发送虚拟ajax请求

$.ajax({

url: 'TestUrl',
type: 'GET',
success: function (data) {
            // Go ahead with you request
},
error: function (x, y, z) {
    if (x.status == 0) {
        alert("Please connect to the internet");
    }
   else{
       alert("Other Error Occured")
    }
 }
});

当连接发生变化时,Phonegap也会onlineoffline被触发