【问题标题】:JavaScript: Automatically Redirect a Page with Post ParametersJavaScript:使用帖子参数自动重定向页面
【发布时间】:2015-05-24 06:16:18
【问题描述】:

我有一个如下页面:

<html>
<head></head>
<body>

  <form name="myform" action="http://www.example.com/page" method="post">
    <input type="hidden" name="param1" value="1">
    <input type="hidden" name="param2" value="2">
    <input type="hidden" name="param3" value="3">
    <input type="submit" value="Click Here If Not Redirect">
  </form>

  <script language="JavaScript">
    document.myform.submit();
  </script>

</body>
</html>

我想要一个 JavaScript 代码(没有 jQuery 什么的,轻量级在我的项目中非常重要)来做上面的事情(使用 POST 参数自动重定向页面)。我不希望用户看到重定向页面。例如这样的:

<html>
   <head>
      <meta http-equiv="refresh" content="0; url=http://www.example.com/page">
      <meta http-equiv="pragma" content="no-cache">
      <meta http-equiv="expires" content="-1">
   </head>
   <body>
   </body>
</html>

当然还有 POST 参数。

我的问题有什么解决办法吗?

【问题讨论】:

  • 如果我正确理解了您的问题,那么您可以使用 window.redirect 并将参数作为查询字符串传递
  • 感谢您的评论。有没有办法发布参数?我上面的第一个代码是 POSTing 参数,但用户看到页面大约 5 到 10 秒。在第二个代码中,我无法发布参数,但用户一看到页面就会重定向(不到一秒)。提前谢谢你。

标签: javascript redirect post parameters


【解决方案1】:

用ajax发送表单

    <html>

    <head></head>

    <body>

      <form name="myform" id="myFormElement" action="http://www.example.com/page" method="post">
        <input type="hidden" name="param1" value="1">
        <input type="hidden" name="param2" value="2">
        <input type="hidden" name="param3" value="3">
        <input type="submit" onclick="submitAjax()">
      </form>

      <script language="JavaScript">
        var form = document.getElementById("myFormElement");
        function submitAjax() {
          var data = new FormData(form);

          var xhr = new XMLHttpRequest();
          xhr.open('POST', 'http://www.stackoverflow.com', true);
          xhr.onload = function() {
            // got a response for the post now redirect the user to 
            // "my portal... so I can do things in my portal... 
            // in the router's little web server."
            window.location.href = "http://wherever.com/you/want/to/go/now";
            console.log(this.responseText);
          };
          xhr.send(data);

        }
        form.onsubmit = function(e){
          e.preventDefault();
          submitAjax();
        }

      </script>

    </body>

    </html>

【讨论】:

  • 我已经说过了,我不希望用户看到该页面。这样他/她必须自己提交表格。
  • 他们不会看到任何其他页面,用户在提交时将停留在同一页面上,而当您收到响应时,您会怎么做
  • 该页面在路由器上,我不能在那里做我的事情。我必须将用户重定向到我的门户(使用来自路由器的参数),这样我才能在我的门户中做事。这个页面将被复制到路由器的小网络服务器中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-19
  • 1970-01-01
  • 2018-11-17
  • 2019-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多