我有一个php代码(还有一点点javascript(,如下所示,其中当第二个用户试图登录表单时,会显示警告消息。
我现在遇到的问题是,单击警告框中的"确定"按钮,它会进入if块,但单击"取消"按钮时,它不会进入else块f块内再次。
<?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。
下面是一个快速入门示例:
index.php
<?php
//....
$user = "John Doe"; // $row['user_name'];
$message = "User $user is logged in. Do you want to take over?";
if (isset($_GET['takeover'])) {
if ($_GET['takeover'] == "confirm") {
// $stmt1 = $connect->pre......etc
exit(json_encode(["message" => "Access confirmed"])); // Send response to JS
} else {
// $stmt1 = $connect->pre......etc
exit(json_encode(["message" => "Access revoked"])); // Send response to JS
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TEST</title>
</head>
<body>
<h1>MY USER INTERFACE</h1>
<script>
const takeover = confirm("<?= $message ?>");
fetch(`?takeover=${takeover ? "confirm" : "revoke"}`)
.then(response => response.json())
.then(data => {
console.log(data);
});
</script>
</body>
</html>
- 服务器将在提供页面之前"剥离"PHP标记,但返回的值将保留。I.e:JavaScript代码中的
$message
- 在文档就绪时,
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();
}
这是您的文章中描述的简单的PHP方法。正如其他酷家伙所说,你可以使用AJAX来不更改URL。