【问题标题】:how can i send the data to another page without appending it in url?如何将数据发送到另一个页面而不将其附加到 url?
【发布时间】:2012-10-08 08:13:17
【问题描述】:

我有一个场景,当用户点击一个链接时,他被定向到一个页面,我想在其中添加代码以获取变量并重定向到另一个页面。

.即用户点击<a href="sample.tpl">click here</a>

在 sample.tpl 我想写一个代码把他重定向到另一个页面

<script>
window.location="http://mydomain.com/?page_id=10"

但出于安全原因,我也想在这个新链接上发送一个变量而不将其附加到 url

我怎样才能通过一些安全的程序来做到这一点。

如果不清楚,请向我提问。

【问题讨论】:

  • 您是否尝试将其保存在 cookie 中,然后在其他页面中访问它?
  • 目标页面是不是你的? 安全原因是什么意思?
  • 是的,目标页面是我的,如果 cookie 被禁用会怎样
  • 如果您准确解释您要做什么以及为什么这样做可能会有所帮助,可能会有更好的完整解决方案。除非您使用 SSL 上的表单,否则网络世界中没有多少是真正安全的。
  • 实际上我希望只有注册用户才能看到该页面,但该用户身份验证来自另一个数据库。所以我不希望它附加到 url,因为任何人都会来访问该页面

标签: javascript javascript-events


【解决方案1】:

您可以使用method="post"、带有您要传递的值的hidden 输入以及样式为常规链接的submit 按钮创建一个表单(如果您还想手动发送表单)。

然后只需手动或通过submit() 方法以编程方式提交表单


示例(页面加载后 3 秒后自动重定向) http://jsbin.com/avacoj/1/edit

HTML

<form method="post" action="http://mydomain.com/" id="f">
   <input type="hidden" name="page_id" value="10">
   <noscript><button type="submit">Continue</button></noscript> /* see below */
</form>

Js

window.onload = function() {
  var frm = document.getElementById('f');
  setTimeout(function() {
      frm.submit();
  }, 3000);
};

作为旁注,您可以考虑在 &lt;noscript&gt;&lt;/noscript&gt; 标记内插入一个 submit 按钮,这样即使用户设备上没有 js 也可以进行重定向,因此页面仍然可以访问。

【讨论】:

  • 好主意,让我试试,然后会回来评论或标记为答案,同时如果你能提供一个例子,将不胜感激
【解决方案2】:

在 Fabrizio 的回答之外,有人编写了一个 javascript 函数,它允许您构建表单并在运行时通过 POST 发送它。

POST 类似于GET(变量附加到 url),除了变量是通过标头发送的。仍然可以伪造POST 请求,因此您必须对数据执行某种验证。

function post_to_url(path, params, method) {
    method = method || "post"; // Set method to post by default, if not specified.

    // The rest of this code assumes you are not using a library.
    // It can be made less wordy if you use one.
    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    for(var key in params) {
        if(params.hasOwnProperty(key)) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
         }
    }

    document.body.appendChild(form);
    form.submit();
}

这样使用:

post_to_url("http://mydomain.com/", {'page_id':'10'}, "post");

来源: JavaScript post request like a form submit

【讨论】:

    猜你喜欢
    • 2021-04-15
    • 2021-08-21
    • 2019-03-23
    • 1970-01-01
    • 2020-08-16
    • 1970-01-01
    • 2020-05-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多