2

我的网页“mywebpage.php”是通过“someotherpage.php”的“GET”到达的:

 // In someotherpage.php -- go to mywebpage.php and display the form:
  window.location = "mywebpage.php?someVariable=" + theVariable;

我在“mywebpage.php”中按如下方式处理:

 THIS IS THE 'GET' HANDLER for the form IN "mywebpage.php":
  if(isset($_GET['someVariable']))
  {
       // set up form variables to initial values, then display the form
  }

提交表单后,我重新输入相同的“mywebpage.php”来处理表单的 POST:

  THIS IS THE 'POST' HANDLER IN "mywebpage.php"
  // okay the form was submitted, handle that here...
  if(isset( $_POST['theformSubmitButton']))
  {
         // handle the form submit
  }

问题是当用户提交表单时,仍然调用 GET 处理程序,因此表单被重新初始化。

原因是,当用户 POST 的表单时,GET['someVariable'] 仍然存在,因此重新输入 GET 处理程序,然后处理 POST 处理程序代码,但此时 GET 处理程序重新初始化了表单这让用户感到困惑,因为他们刚刚完成了将表单的值从初始设置中更改出来。

换句话说,当表单提交时,POST 数组被正确填充,但 GET 数组仍然存在,它的旧变量仍然存在,包括“someVariable”

所以我在 GET 处理程序中添加了一个“未设置”调用:

 this is the MODIFIED 'GET' HANDLER in "mywebpage.php"
  if(isset($_GET['someVariable']))
  {
       // set up form variables then display the form

       // now clear out the 'someVariable' in the GET array so that 
       // when the user POST's the form, we don't re-enter here
       unset($_GET['someVariable']));
  }

这无法正常工作。发布表单时,我仍然看到上面的 GET 处理程序被调用。

我需要确保提交表单时,不会重新调用 GET 处理程序——为什么上面的“unset()”代码不起作用?

编辑:这是表格,不仅仅是重要部分(我遗漏了很多输入,几个 img 标签等,仅此而已):

 <form enctype="multipart/form-data" action="#" style="display: inline-block"
         method="post" name="myForm" id="myFormId">

  <textarea name="InitialText" id="theText" rows="4" cols="68"
       style="border: none; border-style: none"></textarea>
  <br />
  <label style="font-weight: bold; font-style: italic">For more info provide an email addres:</label>
  <input type="text" id="emailField" name="emailFieldName" value="you@gmail.com" />
  <input type="submit" id="theformSubmitButton" name="theformSubmitButton" value="Post Now">
  </form> 
4

3 回答 3

4

GET 请求和 $_GET 变量位于两个不同的层。

当您的用户被定向到 mywebpage.php 时,会有数据通过 get 传递。到目前为止还可以,但是数据仍然在您的用户当前 URL 中。您可以通过查看地址栏看到这一点。?someParameter=someValue地址末尾会有一个。

unset 功能仅适用于您的服务器,并且仅适用于您的脚本的一次性执行。它不会从您的用户浏览器中的 URL 中删除 GET 信息。

当您通过 HTML 表单提交数据时,会将用户重定向到相同的 url,其中包括 GET 数据,该数据存在,但正在重新提交

尝试设置:

<form action="mywebpage.php" method="post">

这将为您的 html 表单设置一个自定义目标,从而删除 GET 信息。

于 2013-09-08T19:49:54.900 回答
0

我会尽可能避免使用$_POST或直接使用。$_GET原因:您可以过滤/修改全局请求。简单示例:

$myPost = $_POST;
$myGET  = $_GET;
unset($myGET["someVariable"]);

一般来说:你为什么同时使用$_GET$_POST?如果你必须这样做,你可以用if,if else和来处理它else

于 2013-09-08T19:45:50.117 回答
0

那是因为你取消了变量但是

window.location = "mywebpage.php?someVariable=" + theVariable;

是一样的。

我的猜测是,当变量未设置为具有以下内容时,您需要进行更改:

window.location = "mywebpage.php";
于 2013-09-08T19:47:54.517 回答