JS / jQuery提交由PHP处理的表单的示例


Example of JS / jQuery to submit a form handled by PHP

我有这样的PHP代码:(用于签出-位于PHP页面中与其他PHP处理程序一起用于不同的功能,此文件包含在页面中,如index.php或其他相关页面。)

if(isset($_POST['signout'])) { // logout button
  // Clear and destroy sessions and redirect user to home page url.
  $_SESSION = array();
  session_destroy();
  // redirect to homepage (eg: localhost)
  header('Location: http://localhost/index.php');
  }

我通常使用<form action="index.php" method="post">,其中功能当前包含和<input type="submit" name="signout">用于此类事情,但这次我想使用锚标记,如:<a href="" >Sign Out</a>用于签出。

有没有人愿意展示一个示例代码,将触发提交,将由上面给定的PHP代码处理。

jQuery或Javascript解决方案都可以。

使用POST提交身份验证令牌有很好的理由,这通常会启动或更改会话状态——但这些并不真正适用于关闭会话的问题——为什么不直接通过GET触发它呢?

但是如果你真的必须做POST,你真的必须通过一个href来做(而不是样式化一个提交按钮),你真的必须通过javascript来做(如果客户端禁用了javascript,这将会中断),那么…

<script>
function sendForm(formId) 
{
   if (document.getElementById(formId).onsubmit()) 
      document.getElementById(formId).submit();
}
<script>
<form id='logout'>
<input type='hidden' name='signout' value='1'>
</form>
<a href="javascript:sendForm('logout');">logout</a>