如何获取原始查询字符串数据并使用它来构建 iframe 源?

How to get raw query string data and use it to build iframe source?

我有一个客户场景,我试图将查询字符串数据从表单 1 传递到表单 2,以便用联系信息预填充第二个表单。表单 2 位于第一个表单的 "thank you" 页面上。

以下是 URL 在用户提交第一个表单并被重定向到下一页后的处理方式...

http://website.com/thanks/?a=First+Last&b=name%40website.com

下面是表单最初在 iframe 中加载到该页面的方式

<iframe id="form2" src="http://website.com/form2" width="315px" height="340px" frameborder="0" marginheight="30" scrolling="no" sandbox="allow-forms allow-scripts allow-top-navigation"></iframe>

我目前在脚本上的尝试是从 URL 获取查询字符串数据而不对其进行解码 (using an answer from stack overflow),然后使用查询字符串数据重建 iframe 的源代码,因此表单 2 具有要提取的查询字符串数据,并且可以预先填写。

<script type="text/javascript">

var QueryString = function () {
  // This function is anonymous, is executed immediately and 
  // the return value is assigned to QueryString!
  var query_string = {};
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
        // If first entry with this name
    if (typeof query_string[pair[0]] === "") {
      query_string[pair[0]] = pair[1];
        // If second entry with this name
    } else if (typeof query_string[pair[0]] === "string") {
      var arr = [ query_string[pair[0]], pair[1] ];
      query_string[pair[0]] = arr;
        // If third or later entry with this name
    } else {
      query_string[pair[0]].push(pair[1]);
    }
  } 
    return query_string;
} ();

window.onload = function loadSite() {
document.getElementById('form2').src = 'http://website.com/form2' + '?a=' + QueryString.a + '&b=' + QueryString.b;
}

</script>

这应该像这样重建 iframe 代码...

<iframe id="form2" src="http://website.com/form2/?a=First+Last&b=name%40website.com" width="315px" height="340px" frameborder="0" marginheight="30" scrolling="no" sandbox="allow-forms allow-scripts allow-top-navigation"></iframe>

但由于某种原因,它不起作用。重建 iframe 源的函数不是 运行,我怀疑它与脚本如何获取查询字符串数据有关。

您认为有什么原因吗?或者有更好的方法来解决这个问题吗?

感谢您的帮助! :)

如果你只是想要查询,为什么要把它拆开再装回去?

只需使用

var qs = window.location.search;
var myUrl = "http://www.example.com" + qs;
document.getElementById('form2').src = myUrl;