【问题标题】:GET to POST not workingGET 到 POST 不起作用
【发布时间】:2013-09-27 20:33:27
【问题描述】:

我想发出 get 请求来发布以下代码的请求 -

       <html>
       <head>
         <script language="JavaScript">
          function redirect()   {
             if (window.focus)
           self.focus();
                this.location = '/test/GetReports?id=       
           <%=System.currentTimeMillis()+session.getId()%>';
         }
      </script>
    <title>Downloading Document</title>
         </head>
   <body marginwidth='0' marginheight='0' onload='javascript:redirect()'>
   </body>
 </html>

为了实现这一点,我在下面做了 -

   <html>
   <head>
     <script language="JavaScript">
     function redirect()    {
     if (window.focus)
        self.focus();
      location =  '/test/GetReports?id=<%=System.currentTimeMillis()+session.getId()%>';
      var form = document.createElement("form");
      form.setAttribute("method", "post");
      form.setAttribute("action", location);
       form.submit();
      }
   </script>
   <title>Downloading Document</title>
   </head>
    <body marginwidth='0' marginheight='0' onload='javascript:redirect()'>
  </body>
 </html>

但这并没有什么区别。这个请求仍然是Get。请让我知道还需要做什么。

感谢您的帮助!

【问题讨论】:

  • 在 Chrome 控制台上测试这个 form.setAttribute("method", "post"); 看看它是否有效
  • 只是指出,脚本元素上的language 属性已过时。你应该改用type="text/javascript"
  • 你第二次尝试还有效吗?我看不到它是如何发送 GET 请求的
  • 我已经使用您的代码进行了测试,它工作正常 :) 唯一的区别是我的位置指向另一个位置。

标签: javascript http post get


【解决方案1】:

您实际上是使用 POST 表单发送 GET 数据。 URL 中指定的参数始终被视为 GET 数据。

为了说明这意味着什么,如果您有一个如下所示的表单:

<form method="post" action="test.html?gid=1">
    <input name="pid" value="2">
</form>

...服务器将接收值 gid 作为 GET 和 pid 作为 POST。无论表单使用什么方法,URL 中的任何内容都会作为 GET 发送。

因此,要使您的代码正常工作,您需要在表单内创建一个字段,以使其将数据作为 POST 发送。

function redirect() {
    if (window.focus) self.focus();
    loc = '/test/GetReports';   // note: no parameters here
    var form = document.createElement("form");

    // create the input element
    var input = document.createElement("input");
    input.setAttribute("name", "id");
    input.setAttribute("value", <%=System.currentTimeMillis()+session.getId()%>);
    form.appendChild(input);

    form.setAttribute("method", "post");
    form.setAttribute("action", loc);
    form.submit();
}

另请注意,我将location 重命名为loc --- 否则您可能会遇到问题,因为location 将指向window.location

【讨论】:

  • 谢谢大家的帮助!我尝试了上面的代码,但 redirect() 函数本身没有被执行。上面的这个jsp是从一个servlet调用的,这个servlet正在从JS打开一个新的弹出窗口。下面的代码 sn-p 正在打开新窗口,然后调用上面的 jsp。 var f = document.getElementById('Form1'); loc = '/ocs/Displayservlet?AcctNum='+acctNum+'; f.setAttribute("方法", "post"); f.action = 位置; parent.window.open('','TheNewWindow','width=640,height=480,toolbar=no);f.submit();所以这个servlet调用是post但是当我尝试上面的代码然后redirect()不行。有什么线索吗?
  • 有人能说明一下吗?
  • 这与原始问题完全无关。请将其作为新问题发布。
  • 我能够解决问题。我不得不添加 document.body.appendChild(form);并且缺少双引号 input.setAttribute("value", "");感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-01
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
相关资源
最近更新 更多