PHP-根据用户单击的按钮返回true或false

PHP - Return true or false depending on which button user clicked

本文关键字:返回 true false 按钮 用户 单击 PHP-      更新时间:2023-12-12

我正在尝试制作JavaScript confirm()命令的PHP版本:

<!DOCTYPE html>
<?php
    function confirm($title, $text) {
        $html = '<div id="alert" style="background-color:white; text-align:center; height:400px; width:300px; color:black; position:fixed; top: 0; left:50%; margin-left:-150px; border:1px solid black; box-shadow: 5px 5px 10px gray;">';
        $html = $html . '<h1 style="background-color:red; border-radius: 15px;">'. $title . '</h1>';
        $html = $html . '<span style="font-size: 20px;">The page at ' . $_SERVER['SERVER_NAME'] . ' says...</span><br><br>' . $text;
        $html = $html . '<br><br><button type="button" style="border-radius:25px; height:50px; width:100px; background-color:lightGray; border:1px solid black;" onclick="this.parentNode.style.display=''none''">OK</button>';
        $html = $html . '<button type="button" style="border-radius:25px; height:50px; width:100px; background-color:lightGray; border:1px solid black;" onclick="this.parentNode.style.display=''none''">Cancel</button>';
        echo $html;
    }
?>

如何根据用户单击的按钮返回true或false?

还有另一种不那么容易混淆的方法来制作html

$html = '<div id="alert" style="background-color:white; text-align:center; height:400px; width:300px; color:black; position:fixed; top: 0; left:50%; margin-left:-150px; border:1px solid black; box-shadow: 5px 5px 10px gray;">';
$html.= '<h1 style="background-color:red; border-radius: 15px;">'. $title . '</h1>';
$html.= '<span style="font-size: 20px;">The page at ' . $_SERVER['SERVER_NAME'] . ' says...</span><br><br>' . $text;
$html.= '<br><br><button type="button" style="border-radius:25px; height:50px; width:100px; background-color:lightGray; border:1px solid black;" onclick="this.parentNode.style.display=''none''">OK</button>';
$html.= '<button type="button" style="border-radius:25px; height:50px; width:100px; background-color:lightGray; border:1px solid black;" onclick="this.parentNode.style.display=''none''">Cancel</button>';
echo $html;  

EDIT-要在php中从用户那里获取值,必须使用ajax、表单或_get协议。请注意,一旦出现在屏幕上,您的html代码就不再链接到任何php脚本。php函数在调用期间执行,而javascript函数在客户端执行。您不能从页面中调用函数并在php函数中使用返回值。您可以做的是在单击按钮时重新加载页面,并在url中显示所需的值。注意onclick属性。

<button type="button" style="border-radius:25px; height:50px; width:100px; background-color:lightGray; border:1px solid black;" onclick="window.location.href='yourscript.php?confirm=false'">Cancel</button>
<button type="button" style="border-radius:25px; height:50px; width:100px; background-color:lightGray; border:1px solid black;" onclick="window.location.href='yourscript.php?confirm=true'">OK</button>

此外,你的按钮可以被锚取代,就像这样(它们可以和你的按钮有完全相同的样式):

<a href="yourscript.php?confirm=false">cancel</a>
<a href="yourscript.php?confirm=true">OK</a>

使用这两种方法,您可以在php脚本中检索这样的值:

$confirm = (isset($_GET['confirm']) ? $_GET['confirm'] : '');