2015-10-04 56 views
0

我試圖根據本地存儲中特定密鑰的存在生成html內容。代碼如下:本地存儲密鑰驗證在Firefox中失敗

// Check if the user is signed in or not 
    if(localStorage.getItem("token") === null) { 
     document.getElementById("main").innerHTML = document.getElementById("welcomeview").innerHTML; 
    } else { 
     document.getElementById("main").innerHTML = document.getElementById("profileview").innerHTML; 
    } 

縱斷面圖總是顯示,即使沒有在本地存儲無令牌密鑰集:

localStorage 
Storage { token: "undefined", length: 1 } 

爲什麼?

編輯:

令牌被設定與AJAX請求的響應值:

function sign_in() { 

     var uri, method, formId, $form, form_data; 

     uri = location.protocol + '//' + location.host + "/sign_in"; 
     method = "POST"; 
     formId = "#signin_form_id"; 

     $form = $(formId); 
     form_data = get_form_data($form); 

     // Set-up ajax call 
     var request = { 
      url: uri, 
      type: method, 
      contentType: "application/json", 
      accepts: "application/json", 
      cache: false, 
      dataType: 'json', 
      data: form_data 
     }; 
     // Make the request 
     $.ajax(request).done(function(data) { // Handle the response 
      // Attributes are retrieved as object.attribute_name 
      // alert(obj.count); 
      if(data.successSignIn === false) { 
       // Login failed we show the welcome page 
       alert(data.message); 
       document.getElementById("main").innerHTML = document.getElementById("welcomeview").innerHTML; 
      } else { 
       // Login succeeded. We load the user's info, his messages and also a form in which he can type messages 
       // Save the token received from the server. Could also be stored as a cookie 
       localStorage.setItem('token', data.token); 
       // Go to the home page 
       go_home(); 
      } 
     }).fail(function(jqXHR, textStatus, errorThrown) { 
        console.log(JSON.stringify(jqXHR)); 
        console.log("AJAX error: " + textStatus + ' : ' + errorThrown); 
       } 
     ); 
     location.reload(); 

} 
+0

令牌密鑰被設置,並且是一個字符串'「undefined」' – lshettyl

+2

只需要替換'if(localStorage.getItem(「token」)){...}' –

+0

@Sherali Turdiyev謝謝我解開了關鍵的價值和思想鑰匙也將被刪除 – Sebi

回答

1

被修改:嘗試此設定項目localStorage.setItem("token", typeof undefined === data.token ? undefined : data.token)。避免使用字符串"undefined"

我建議:

1)更換if(localStorage.getItem("token")) {...}

3)此外,您還可以通過三元操作

var welcomeText = document.getElementById("welcomeview").innerHTML, 
profileText = document.getElementById("profileview").innerHTML; 

document.getElementById("main").innerHTML = (localStorage.getItem("token")) ? welcomeText : profileText 
1

做你的榜樣你永遠不會進入if部分爲"undefined" === null總是假的。

你想檢查你的情況下if(localStorage.getItem("token") === "undefined")