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

chu*_*tar 40 html javascript php anchor hyperlink

我希望当用户点击链接时,页面运行一些PHP代码,而不重定向它们.这有可能吗?

<a href=""></a>
Run Code Online (Sandbox Code Playgroud)

或者使用javascript onclick事件?

Par*_*ots 97

是的,你需要一个由onclick触发的javascript函数来执行页面的AJAX加载然后返回false,这样它们就不会被重定向到浏览器中.您可以在jQuery中使用以下内容,如果这对您的项目是可接受的:

<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function doSomething() {
    $.get("somepage.php");
    return false;
}
</script>

<a href="#" onclick="doSomething();">Click Me!</a>
Run Code Online (Sandbox Code Playgroud)

如果需要使用表单值,也可以进行回发(使用$ .post()方法).

  • 你应该从函数返回false,所以不遵循HREF. (6认同)
  • 2年后,现在我意识到是什么让这个很好的答案! (5认同)
  • @Parrots:如果我想将ID传递给somepage.php,我该如何实现?假设我将"a"链接更改为onclick ="doSomething(<?php echo $ id?>);" 以及如何将其传递给php页面?谢谢 (2认同)

Roy*_*ico 10

正如其他人所建议的那样,使用JavaScript来进行AJAX调用.

<a href="#" onclick="myJsFunction()">whatever</a>

<script>
function myJsFunction() {
     // use ajax to make a call to your PHP script
     // for more examples, using Jquery. see the link below
     return false; // this is so the browser doesn't follow the link
}
Run Code Online (Sandbox Code Playgroud)

http://docs.jquery.com/Ajax/jQuery.ajax


Tho*_*key 7

如果尚未安装jquery(因为您只是初学者或其他东西),请使用以下代码:

<a href="#" onclick="thisfunction()">link</a>

<script type="text/javascript">
function thisfunction(){
    var x = new XMLHttpRequest();
    x.open("GET","function.php",true);
    x.send();
    return false;
}
</script>
Run Code Online (Sandbox Code Playgroud)

  • 如果您不使用jquery,您的初学者怎么样?我喜欢使用Javascript,而不喜欢它,因为我很笨 (4认同)
  • 事后看来,+ 1。我已经意识到冗余依赖jQ有多少,特别是看到Web标准已经走了多远。 (2认同)

Ale*_*nch 5

我知道这篇文章很旧,但是我只想补充我的答案!

您说过将用户注销而不直接执行...该方法可以重定向,但会将用户返回到他们所在的页面!这是我的实现:

// every page with logout button
<?php
        // get the full url of current page
        $page = $_SERVER['PHP_SELF'];
        // find position of the last '/'
        $file_name_begin_pos = strripos($page, "/");
        // get substring from position to end 
        $file_name = substr($page, ++$fileNamePos);
    }
?>

// the logout link in your html
<a href="logout.php?redirect_to=<?=$file_name?>">Log Out</a>

// logout.php page
<?php
    session_start();
    $_SESSION = array();
    session_destroy();
    $page = "index.php";
    if(isset($_GET["redirect_to"])){
        $file = $_GET["redirect_to"];
        if ($file == "user.php"){
            // if redirect to is a restricted page, redirect to index
            $file = "index.php";
        }
    }
    header("Location: $file");
?>
Run Code Online (Sandbox Code Playgroud)

然后我们去!

从完整网址获取文件名的代码不是错误的证明。例如,如果查询字符串中包含未转义的“ /”,它将失败。

但是,有很多脚本可以从url获取文件名!

编码愉快!

亚历克斯