2

I have a login page and i want to store user information. If user is null, send user to login page, else user will continue to use application.

$.mobile.changePage("index.html"); 

My code is:

var obj; //user information (json)
$(document).ready(function(e) {
$("#btnlogin").click(function(){
            var username=$("#lusername").val();
            var password=$("#lpassword").val();
        $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "Service1.asmx/Giris",
        data: "{'kullaniciadi':'"+ username+"' , 'sifre': '"+password+"'}",
        dataType: "json",
        success: function(msg) {



             obj = jQuery.parseJSON( msg.d);
            if(obj!=null)
            {
                 $.mobile.changePage("index.html");
            }
            else alert("not found");

                                },
        error: function (xhr, ajaxOptions, thrownError) {
        alert(xhr.status);
        alert(thrownError);
      }



        });
    });
});

Because i'm using $.mobile.changePage("index.html"); i can use the same java script at every page, i use alert and i works

$('#illnessDetailsPage').live('pageshow', function(event) {
    alert(user);

});

My problem starts here, i use var obj//user info at the top of javascript but when page is change, it returns null.

Why it is null? (to learn javascript better) and how to solve problem?

Then how to control 'back' button to not load login page while logined? I didnt find any example, Thank You in advance. (I dont want to use localStorage)

4

1 回答 1

4

每当您加载页面时,都会再次加载资源。这实质上意味着您存储在 javascript 变量中的信息将丢失。

现在来到您的解决方案,因为您使用的是 phonegap,因此您的应用程序将在基于 webkit 的浏览器上运行。所以我建议你使用localStorage。

在登录成功函数中,您可以设置 userInfo。

$("#btnlogin").click(function(){
        var username=$("#lusername").val();
        var password=$("#lpassword").val();
    $.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "Service1.asmx/Giris",
    data: "{'kullaniciadi':'"+ username+"' , 'sifre': '"+password+"'}",
    dataType: "json",
    success: function(msg) {
             localStorage.setItem('userInfo', msg.d);
             //Your code here
    }

在其他页面中,您现在可以只检查这个 localstorage 对象。如果为空,则将页面更改为登录页面。

if(localStorage.getItem('userInfo') == null){
   $.mobile.changePage('login.html');
}

我还建议您查看 indexedDb https://developer.mozilla.org/en/docs/IndexedDB

于 2013-10-02T18:26:42.300 回答