2014-02-08 33 views
0

我正在開發一個android應用程序,需要檢測互聯網連接,如果設備沒有互聯網連接會有一個警報,該設備沒有互聯網連接。jQuery手機阿賈克斯檢測,如果設備沒有互聯網連接

這裏是我的代碼:

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

    } 
}); 
+0

我應該在我的代碼的'url:'基礎上放什麼? – user3130849

+0

或可以請你展示我將如何實現這個在我的代碼 – user3130849

+0

你的網址來檢查互聯網 –

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嘩嘩當有在連接更改被激發

+0

我應該在'url:'中放什麼? – user3130849

+0

你的你的服務器....(虛擬URL),JUS來檢查是否有互聯網連接 –