【问题标题】:update iframe form action url when user hit the URL with specific parameter当用户点击带有特定参数的 URL 时更新 iframe 表单操作 url
【发布时间】:2017-02-21 11:04:50
【问题描述】:

这是代码示例

页面网址为:http://example1.com?id=1

<html>
  <body>
    <h1>main page</h1>
    <iframe src="http://example2.com">
      <form id="test" action="http://example3.com?id=1">
        ...
      </form>
    </iframe>
  </body>
</html>

现在我的问题是当用户点击具有不同参数值的页面 URL 时如何更新 iframe 表单操作 URL。(例如,如果用户点击参数 id=2 的 URL,则表单操作 URL 应更改为 id=2,即action="http://example3.com?id=2",

如何做到这一点?

提前致谢。

【问题讨论】:

  • 你可以在jquey中获取参数,然后你可以改变表单的action属性。
  • 将id 参数传递到iframe src。所以&lt;iframe src="http://example2.com?id=2"&gt;。然后您可以使用 javascript 提取 URL 参数并更改 action 属性。或者,您可以更改 iframe src 上的哈希值。这样您就可以使用hashchange 事件来动态更改表单action 属性。

标签: javascript jquery html iframe


【解决方案1】:

你可以试试下面的代码

在 iframe 中添加以下代码。并在准备好的文件上调用它。

  function getQueries () {
  // This function 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]] === "undefined") {
      query_string[pair[0]] = decodeURIComponent(pair[1]);
        // If second entry with this name
    } else if (typeof query_string[pair[0]] === "string") {
      var arr = [ query_string[pair[0]],decodeURIComponent(pair[1]) ];
      query_string[pair[0]] = arr;
        // If third or later entry with this name
    } else {
      query_string[pair[0]].push(decodeURIComponent(pair[1]));
    }
  }
  return query_string;
};

这将返回包含在 url 中传递的参数的对象。

例如

$(document).ready(function(){
    var _curQueries = getQueries();
    if(_curQueries["id"] !== undefined)
    {
        var myForm = document.getElementById('test');
        myForm.action = 'http://example3.com?id='+_curQueries["id"];
    }

    /*
    var _params = "";
    var _counter = 0, _length = _curQueries.length;
    for(var i in _curQueries)
    {
        _params += i+"="+_curQueries[i];
        _counter++;
        if(_counter < _length)
        {
          _params += "&";
        }
    }
    var myForm = document.getElementById('test');
    myForm.action = 'http://example3.com?'+_param;
    */
});

【讨论】:

  • 我无法在 iframe 代码中添加此代码,它是外部 URL,
  • 我没有得到..您正在 iFrame 中加载 example2.com 而 example2.com 不是您的代码吗?你也想改变表单动作来改变相应的参数传递??并且表单只是 iFrame 的一部分吗??
  • 是的,没错,我需要将参数值传递给表单操作 URL。
  • 这是不可能的,因为您无法访问 example2.com。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-10
  • 1970-01-01
  • 1970-01-01
  • 2014-11-24
相关资源
最近更新 更多