带有PHP类的注销按钮

时间:2013-12-26 21:46:52

标签: javascript php class

现在我正在使用jquery来运行一个无效的php脚本,我知道php是一个服务器端脚本,你不能从jquery运行脚本,在这种情况下,什么是最好的方法从浏览器调用类中的php函数?

这是定义注销功能的类

class Profile
{
   private function logout()
   {
       $_SESSION = array();
       session_destroy();
   }

这是我想在点击退出按钮时调用该功能的php页面

<?php

include_once('profileclass.php');
$user = new Profile($name, $id);

?>

<html>
<head> </head>
<body>
     <input type='button' value='logout' id='logout'>

<script>
    $(function() {
      $('#logout').click(function() {
          <?php $user->logout(); ?>
      }
      });
    });
</script>
</body>
</html>

2 个答案:

答案 0 :(得分:4)

不要将PHP与Javascript混合,因为PHP代码是在浏览器在页面上呈现html之前执行的。相反,请使用$_POST全局变量,该变量将包含提交到您网页的数据。

使用:

<?php
include_once('profileclass.php');
$user = new Profile($name, $id);
if ($_POST['logout'] == "<some_value>") {
    $user->logout();
}
?>
<html>
<body>
  <form method="post">
    <input type='submit' value='<some_value>' name='logout'>
  </form> 
</body>
</html>

<强>更新

另外,制作logout方法public,以便可以在Profile课程之外访问:

class Profile {
   public function logout() { // change is in this line
       $_SESSION = array();
       session_destroy();
   }
}

答案 1 :(得分:0)

前端

$('#logout').click(function() {
    $.ajax({
        url:  '/logout.php', // Script where logout calls
        type: 'post'
    });
});

后端(logout.php)

$user = new Profile();
$user->logout();