如何在提交表单后自动刷新页面

时间:2015-06-17 08:13:48

标签: php html forms

我有一个HTML表单,当我点击“更新”时,更改不会反映,需要刷新才能看到更改。 但是当我重新加载时,总是Confirm Form Resubmission

我使用了<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">,这意味着它会在同一页面上提交。

4 个答案:

答案 0 :(得分:1)

您可以通过多种方式刷新页面:

方式:1

if(isset($_POST[submits])) {
    header("location:index.php"); // your current page
}

方式:2

if(isset($_POST['submit'])) {
    //Your SQL Query
    echo "<meta http-equiv='refresh' content='0'>";
}

方式:3 (不推荐)

onsubmit="window.location.reload();"似乎这不起作用。所以我在其中使用超时功能。使其发挥作用。

onsubmit="setTimeout(function() { window.location.reload(); }, 5)"

方式:4

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">

答案 1 :(得分:0)

我倾向于使用AJAX表单提交:

// Bind the submit action
$('#myForm').submit(mySubmitFunction);

// Submit handler
function mySubmitFunction(e) {
    e.preventDefault();

    var form = $(this);

    $.ajax({
            url: form.attr('action'),
            data: form.serialize()
    }).done(function(xhr) {
            // My endpoint returns JSON output
            var responseJSON = false;
            try {
                    responseJSON = $.parseJSON(xhr);
            } catch (error) {}

            if (responseJSON && responseJSON.hasOwnProperty('result') &&
                responseJSON.result) {
                    // The important bit
                    location.reload();
            } else {
                    // Handle error
            }
    });
}

我为此选择了以便能够向用户提供快速反馈。如果您不想使用AJAX,PHP文件中处理表单的简单标题('Location:yourPage.php')就足够了。

答案 2 :(得分:0)

您的页面已经在&#34;更新&#34;之后重新加载,因为Confirm Form Resubmission警告弹出。我想问题是在PHP脚本中你在处理新的Post数据之前显示数据。

答案 3 :(得分:0)

因此,您所描述的主要问题是url请求方法是POST。如果在提交表单后刷新页面,浏览器将再次尝试POST,就像您点击提交按钮一样。

这实际上是一种非常自然的方式来提交数据(生成表单的网址)。大多数开源CMS都会做同样的事情并且具有相同的行为(wordpress,drupal)。

我构建了一个自定义系统,它做了同样的事情,但有一些关于刷新触发“你确定要再次提交此表单”而不是仅仅重新加载表单的投诉。所以我用@Bruce的解决方案解决了这个问题。在输出任何内容之前,在我的页面底部,我会重定向到当前网址。这会将浏览器眼中的上一页更改为GET而不是POST,并阻止重新提交警告。

至于您的数据未更新,您可能在处理帖子之前构建表单。确保处理帖子是您执行的第一个操作。

我的系统与此示例代码非常不同,因此不要指望它可以开箱即用。但它应该给你正确的想法。

<?php
if (isset($_SERVER["REQUEST_METHOD"]) && ($_SERVER["REQUEST_METHOD"] == "POST"))
{
  // Validate my form.
  if ($valid)
  { 
    // Save data on successful validation.

    // Redirect to prevent refresh from triggering another
    // form submission. Optional but helpful.
    redirect($_SERVER['REQUEST_URI']);
  }
  else
  {
    // Not valid no harm in just reloading as the user will be
    // fixing their errors and resubmitting anyway.

    // Generate error messages, etc.
  }
}

// Retrieve your form values here after you have fully processed the POST
// operation.
$values = getDBValues();    

function redirect($path)
{
   // The path should be validated somehow as the user
   // could alter parts of it such as query parameters.
   // For simplicity I'm leaving that part out.
   header('Location: ' . $path);
   die();
}

?>
<html>
<form>
...