2016-08-16 132 views
0

有什麼方法可以知道用戶是否使用knockout js登錄?我如何獲取用戶的數據? 我嘗試這個代碼,如何檢查用戶是否使用敲除登錄

var userId = '<%=HttpContext.Current.Session["user_session"] %>'; 
    alert(userId); 

我把它放在一個視圖模型。但它不起作用。

這裏是請求的PHP代碼,

public function login($email,$pass) 
{ 
    try 
    { 
     $stmt = $this->db->prepare("SELECT * FROM accounts WHERE emailadd=:email LIMIT 1"); 
     $stmt->execute(array(':email'=>$email)); 
     $userRow=$stmt->fetch(PDO::FETCH_ASSOC); 
     if($stmt->rowCount() > 0) 
     { 
     if(password_verify($pass, $userRow['password'])) 
     { 
      $_SESSION['user_session'] = $userRow['id']; 
      return true; 
     } 
     else 
     { 
      return false; 
     } 
     } 
    } 
    catch(PDOException $e) 
    { 
     echo $e->getMessage(); 
    } 
    } 

這裏是js代碼,

function homeViewModel(params) { 
    var self = this; 
    var userId = '<%=HttpContext.Current.Session["user_session"] %>'; 
    alert(userId); 
    return self; 
} 
+1

請包括您的PHP代碼。爲了改善您在問題中得到的響應,考慮進行發佈[最小化,完整且可驗證的示例]這樣的內容(http://stackoverflow.com/help/mcve ),[語法突出顯示](http://meta.stackexchange.com/questions/184108/what-is-syntax-highlighting-and-how-does-it-work),在標題中明確提出您的問題,[添加必要標籤](http://stackoverflow.com/help/tagging)...和[標題的常見問題解答](http://stackoverflow.com/help/how-to-ask)以獲取更多信息 – user919426

+0

' HttpContext.Current.Session'這是從哪裏來的,複製粘貼沒有理解? – cske

+0

我在一些stackoverflow問題中看到它。一個人說,需要將HttpContext.Current .Session分配給一個javascript變量。所以我試圖把它放在我的視圖模型中。 – JMA

回答

0

如果homeViewModel在外部JavaScript文件,那麼你不能執行PHP定義。

您必須執行類似以下操作(未測試)。

1)的index.php

<html> 
<head> 
    <title>PHP Test</title> 
    <script type="text/javascript"> 
    window.currentUser = '<%=HttpContext.Current.Session["user_session"] %>' 
    </script> 
    <script type="text/javascript" src="my-vm.js"> 
    </script> 
</head> 
<body> 
    <p data-bind="text: user"></p> 
</body> 
</html> 

2)我-vm.js

function homeViewModel(params) { 
    var self = this; 
    self.user = ko.observable(window.currentUser); 
    return self; 
} 
ko.applyBindings(new homeViewModel()); 

話雖如此,你需要考慮如何管理範圍。將任意變量附加到window並不是一個好主意。