duandi4238 2016-08-16 16:45
浏览 49
已采纳

如何检查用户是否使用knockout登录

Is there any way to know if the user is logged in using knockout js? How can I get the user's data? I tried this code,

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

I put it in a view model. But it is not working.

Here is the requested PHP code,

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

And here is the js code,

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

1条回答 默认 最新

  • 普通网友 2016-08-17 09:45
    关注

    If homeViewModel is defined in an external javascript file then you can't execute php.

    You'll have to do something similar to the following (Not Tested).

    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) my-vm.js

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

    Having said this you'll want to consider how you manage the scope. Attaching arbitrary variables to window isn't a great idea going forward.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样