单击HTML链接触发PHP功能

far*_*oer 4 html php function

是否可以通过单击链接来触发PHP功能?或者我应该坚持表单提交方法?如果单击该链接将起作用,链接应该指向何处?

这是一个示例代码:

<?php
    session_start();
    function listMe($username){
        $username = mysql_real_escape_string($username);
        $query = mysql_query("INSERT INTO List (Usernames) VALUES ('$username')") or die(mysql_error());
    }
?>

<html>
    <head>
        <title>SAMPLE</title>
    </head>
    <body>
        <a href="**__???___**">Add my username to the list</a>
        <?php 
            listMe($_SESSION['Username']); 
        ?>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

也许有人可以指出我正确的方向.谢谢!

Zac*_*old 9

您可以通过使用表单提交再次加载整个页面,或者通过直接将特定页面内容加载到页面中而无需从一个页面到另一个页面来完成此操作.第二种方法称为"AJAX"(Asynchoronous Javascript和XML).这是两个例子,每个例子都有一个.

表单提交方法

form.php的

<?php
function get_users(){
}
if(isset($_GET['get_users']))
{
    get_users();
}
?>
...
<form method="get">
    <input type="hidden" name="get_users">
    <input type="submit">
</form>
Run Code Online (Sandbox Code Playgroud)

AJAX方法

ajax_file.php

<?php
function call_me(){
    // your php code
}
call_me();
?>
Run Code Online (Sandbox Code Playgroud)

form.html

<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
    var xmlhttp;
    if (window.XMLHttpRequest)
    {
        xmlhttp = new XMLHttpRequest();
    }
    else
    {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function()
    {
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
            // do something if the page loaded successfully
        }
    }
    xmlhttp.open("GET","ajax_file.php",true);
    xmlhttp.send();
}
</script>
</head>
<body>
<a href="#" onclick="loadXMLDoc()">click to call function</a>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)


got*_*itz 6

您可以将其作为链接的查询参数传递. http://example.com/?command=listMe&username=tom 但是这样每个人都可以通过加载该URL来运行该功能

<a href="http://example.com/?command=listMe&">List me</a>
Run Code Online (Sandbox Code Playgroud)

并在PHP中

<?php
if( isset($_GET['list_me']) && isset($_SESSION['Username'] ) ){
   listMe( $_SESSION['Username'] );
}
?>
Run Code Online (Sandbox Code Playgroud)


pow*_*uoy 5

HTML

<a href="?list_me">list me</a>
Run Code Online (Sandbox Code Playgroud)

PHP

<?php
if (isset($_GET['list_me'])) listMe();
Run Code Online (Sandbox Code Playgroud)