对不同页面上的结果消息使用 URL 参数?有什么更好的方法来实现这一目标


Using a URL parameter for a results message on different page? What is a better way to accomplish this?

我有一个应用程序,我在其中使用 URL 参数在特定操作和重定向后触发结果消息。示例流如下所示:

1. User fills out form and clicks "Update"
2. [PHP code to update DB]
3. header('Location: [next-page.php]?message=1')
4. [PHP code on checks DB for the text of message id #1 and echo the message, (e.g. "Update successful!")]

这最初效果很好,但有几个问题。URL 参数在显示消息后保留,因此,如果刷新页面,或者用户稍后单击返回该页面,则消息将再次显示。我正在寻找一种方法来执行我上面描述的操作,但仅在第一次显示消息。我想避免为每个结果消息创建一个数据库实体,其中包含一个属性,用于它是否已被查看,因为这似乎有点矫枉过正。你会如何处理这个问题?

一种方法是将表单发布到下一页.php,然后在页面上执行以下代码:

if (isset($_POST['form_element']))
    include("form-process.php"); //Or whatever page the DB update goes in

编辑:你也可以用Javascript来做。将其放在表单所在的页面上:

$("#ajax_submit").click(function(){
    $("#ajax_form").submit();
    window.location=location.protocol+'//'+location.host+location.pathname+"nextpage.php";
});

在表单如下所示的页面上:

<form action="process_form.php" method="POST" id="ajax_form">
    Name: <input name="username"><br>
    Password: <input name="password" type="password"><br>
    <input type="submit" value="Login" id="ajax_submit">
</form>