猿问

带有确定和取消按钮的 php 警告框

我有一个php 代码(还有一点点 javascript),如下所示,当第二个用户尝试在一个用户已经登录的情况下登录表单时,会显示一条警告消息。


我现在遇到的问题是在警告框中单击“确定”时,它会进入if 块,但在单击“取消”时它不会进入else 块,而是再次进入if 块。


<?php

    $message = "user " . $row['user_name'] . " is logged in. Do you want to take over ?";

    echo "<script type='text/javascript'>confirm('$message');</script>";

    if(confirm)

    {

        $stmt1=$connect->prepare("UPDATE trace_users SET write_access='0' WHERE write_access='1'"); // revoke write access of all users

        $stmt1->execute();

    }

    else

    {

        echo "I am in else block";  // Line A

        $stmt1=$connect->prepare("UPDATE trace_users SET write_access='1' WHERE write_access='0'"); // revoke write access of all users

        $stmt1->execute();

    }

?>

为了调试目的,我添加了A 行/B 行。单击“确定”按钮将调用线路 A,单击“取消”按钮将再次调用线路 A。


红颜莎娜
浏览 155回答 2
2回答

长风秋雁

这是一个帮助您入门的简单示例:index.php<?php//....$user =&nbsp; "John Doe"; // $row['user_name'];$message = "User $user is logged in. Do you want to take over?";if (isset($_GET['takeover'])) {&nbsp; &nbsp; if ($_GET['takeover'] == "confirm") {&nbsp; &nbsp; &nbsp; &nbsp; // $stmt1 = $connect->pre......etc&nbsp; &nbsp; &nbsp; &nbsp; exit(json_encode(["message" => "Access confirmed"])); // Send response to JS&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; // $stmt1 = $connect->pre......etc&nbsp; &nbsp; &nbsp; &nbsp; exit(json_encode(["message" => "Access revoked"])); // Send response to JS&nbsp; &nbsp; }}?><!DOCTYPE html><html><head>&nbsp; <meta charset="UTF-8">&nbsp; <meta name="viewport" content="width=device-width, initial-scale=1.0">&nbsp; <title>TEST</title></head><body>&nbsp; <h1>MY USER INTERFACE</h1>&nbsp; <script>&nbsp; &nbsp; const takeover = confirm("<?= $message ?>");&nbsp; &nbsp; fetch(`?takeover=${takeover ? "confirm" : "revoke"}`)&nbsp; &nbsp; &nbsp; .then(response => response.json())&nbsp; &nbsp; &nbsp; .then(data => {&nbsp; &nbsp; &nbsp; &nbsp; console.log(data);&nbsp; &nbsp; &nbsp; });&nbsp; </script></body></html>服务器将在提供页面之前“剥离”PHP 标记,但回显值将保留。即:$message在 JavaScript 代码中。在 Document 上准备confirm()触发器,在 JS 中携带一个布尔值。根据该值,只需使用 GET 请求获取相同的文件(或任何其他文件)somepagename.php?takeover=confirm在 PHP 中侦听$_GET请求并使用 JSON 响应响应 AJAX 请求。打开控制台,查看服务器以足够的消息对象数据响应。快乐的编码。

呼如林

在你的 userpage.php 你有登录:<a href="confirm_login.php?user_name=" . $row['user_name']>Log In</a>在您的 confirm_login.php 中,您可以通过以下两个选项进行确认:$message = "user " . $_GET[user_name] . " is logged in. Do you want to take over ?";<a href="userpage.php?confirm=yes">Yes</a><a href="userpage.php?confirm=no">No</a>现在,当您选择选项时,您将重定向回 userpage.php:if ( $_GET[confirm] == "yes" ) {    $stmt1=$connect->prepare("UPDATE trace_users SET write_access='0' WHEREwrite_access='1'");    $stmt1->execute();} else if ( $_GET[confirm] == "no" ) {    $stmt1=$connect->prepare("UPDATE trace_users SET write_access='1' WHERE write_access='0'"); // revoke write access of all users    $stmt1->execute();  }您可以使用 AJAX 来不更改 URL。
随时随地看视频慕课网APP
我要回答