当前位置: 动力学知识库 > 问答 > 编程问答 >

android - jQuery mobile ajax detecting if device has no internet connection

问题描述:

I'm developing an android app that needs to detect internet connection and if the device has no internet connection there will be an alert that the device has no internet connection.

here is my code:

<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>

I tried it combining it here but it's not working:

<script>

var online = navigator.onLine;

if(online) {

//I placed the ajax here

} else {

alert("Internet Connectivity is not available.");

}

</script>

Please help me achieve this. And I'm using build.phonegap.com in exporting apk file.

Thanks in advance.

网友答案:
 var condition = navigator.onLine ? "ONLINE" : "OFFLINE";

you will get online or offline and can use it accordingly. Also you test it by making an ajax call

$.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");
        }

    }
});
网友答案:

try sending dummy ajax request before you send an actual request

$.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 also have online and offline whish is fired when there is a change in connectivity

分享给朋友:
您可能感兴趣的文章:
随机阅读: