猿问

用户单击链接时如何运行PHP代码?

我想让页面在用户单击链接时运行一些PHP代码,而不重定向它们。这有可能吗


<a href=""></a>

或使用javascript onclick事件?


蓝山帝景
浏览 1159回答 3
3回答

ABOUTYOU

是的,您需要有一个onclick触发的javascript函数,该函数会对页面进行AJAX加载,然后返回false,这样就不会在浏览器中将其重定向。如果您的项目可以接受,则可以在jQuery中使用以下内容:<script type="text/javascript" src="jquery.min.js"></script><script type="text/javascript">function doSomething() {&nbsp; &nbsp; $.get("somepage.php");&nbsp; &nbsp; return false;}</script><a href="#" onclick="doSomething();">Click Me!</a>如果需要使用表单值(使用$ .post()方法),也可以进行回发。

杨魅力

我知道这篇文章很旧,但是我只想补充我的答案!您说要注销用户而不直接执行...该方法可以重定向,但会将用户返回到他们所在的页面!这是我的实现:// every page with logout button<?php&nbsp; &nbsp; &nbsp; &nbsp; // get the full url of current page&nbsp; &nbsp; &nbsp; &nbsp; $page = $_SERVER['PHP_SELF'];&nbsp; &nbsp; &nbsp; &nbsp; // find position of the last '/'&nbsp; &nbsp; &nbsp; &nbsp; $file_name_begin_pos = strripos($page, "/");&nbsp; &nbsp; &nbsp; &nbsp; // get substring from position to end&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; $file_name = substr($page, ++$fileNamePos);&nbsp; &nbsp; }?>// the logout link in your html<a href="logout.php?redirect_to=<?=$file_name?>">Log Out</a>// logout.php page<?php&nbsp; &nbsp; session_start();&nbsp; &nbsp; $_SESSION = array();&nbsp; &nbsp; session_destroy();&nbsp; &nbsp; $page = "index.php";&nbsp; &nbsp; if(isset($_GET["redirect_to"])){&nbsp; &nbsp; &nbsp; &nbsp; $file = $_GET["redirect_to"];&nbsp; &nbsp; &nbsp; &nbsp; if ($file == "user.php"){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // if redirect to is a restricted page, redirect to index&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $file = "index.php";&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; header("Location: $file");?>然后我们去!从完整网址获取文件名的代码不是错误的证明。例如,如果查询字符串中包含未转义的“ /”,它将失败。但是,有很多脚本可以从url获取文件名!
随时随地看视频慕课网APP
我要回答