使用 javascript/jquery,将表单变量传递给 iframe src 参数

Posted

技术标签:

【中文标题】使用 javascript/jquery,将表单变量传递给 iframe src 参数【英文标题】:Using javascript/jquery, pass form variables to iframe src parameters 【发布时间】:2017-03-02 23:43:12 【问题描述】:

我有一个这样的 iframe:

<iframe name="report-iframe" id="report-iframe" src="https://reporting.com/embed"   frameborder="0"></iframe>

我想使用表单中的值替换 src 值

<form method="post" target="report-iframe">
<input id="form-type" name="form-type" type="text" />
<input id="form-date" name="form-date" type="date" />
<input type="button" value="Update Report" onclick="javascript_function()"/>
</form>

所以 iframe 的结果来源是:

src="https://reporting.com/embed?param_type=form-type&param_date=form-date"

然后使用传递的参数重新加载 iframe。

如果可能的话,我想只使用 javascript/jquery 来做到这一点。

【问题讨论】:

我们不能为你做这件事,但这个问题有already a topic 【参考方案1】:

这是一个 jQuery 方法。

function javascript_function() 
  $('#report-iframe').attr('src','https://reporting.com/embed?param_type=' + $('#form-type').val() + '&param_date=' +  $('#form-date').val());    
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<iframe name="report-iframe" id="report-iframe" src="https://reporting.com/embed"   frameborder="0"></iframe>


<form method="post" target="report-iframe">
<input id="form-type" name="form-type" type="text" />
<input id="form-date" name="form-date" type="date" />
<input type="button" value="Update Report" onclick="javascript_function()"/>
</form>

【讨论】:

【参考方案2】:

This JSFiddle 完成您的要求。您需要对其进行调整以获得稳健性,但基本上您可以针对表单(我使用 $('form'),但对于实际场景,您可能想要更具体。)并使用 .serialize() 将其值转换为查询字符串,然后将其附加到 iframe 的 src 属性。

编辑:请注意,对于使用.serialize() 的特定示例,您希望#form-type 的name 属性为“param_type”,而#form-date 的name 属性为“参数日期”

【讨论】:

以上是关于使用 javascript/jquery,将表单变量传递给 iframe src 参数的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 javascript/jquery 禁用表单中的所有内容?

防止 PHP/JavaScript/JQuery (PayPal) 中的表单操作

表单标签中的按钮不会提交或响应Javascript / Jquery

使用 Javascript /jQuery 的 Bootstrap 4 表单验证

使用 javascript/jquery 检测 Asp.Net 表单是不是有效

在 Javascript / jQuery 中无法检索 Django 模板变量值