我需要使用 src 属性加载 iframe。我需要将许多附加信息附加到查询中。目前,我只是将所有这些信息放在一个参数中,如下所示:
<iframe src="mywebsite.com/get_iframe?aVeryLongString"></iframe>
但是,aVeryLongString 可以变得很长。一直到我从服务器收到“414(请求 URI 太大)”错误。
有没有办法在不收到此错误的情况下发出此请求?
注意:iframe 的 url 带有它自己的 Content-Security-Policy,所以我不能只使用 srcdoc 而不是 src。除非即使你使用 srcdoc 也有强制 CSP 的方法?
最佳答案
如果 iframe
将包含 HTML,我会倾向于做 Scott marcus mentioned in a comment : 执行 ajax POST 并填充 div
而不是使用 iframe
。
但是,如果您出于某种原因不能这样做(可能有多种原因,尤其是如果 iframe
包含 HTML 以外的内容):
如果 aVeryLongString
是标准 URI 编码的 name1=value1&name2=value2
形式,你可以给 iframe
一个 name
,然后从 JavaScript 代码向它发送一个表单。非常粗略:
<iframe name="the-iframe"></iframe>
<script>
(function() { // Scoping IIFE to avoid creating global vars
var form, input;
form = document.createElement("form");
form.action = "/path/to/the/resource"; // I didn't use your `src` because it's incorrect
form.target = "the-iframe";
for (/*...looping through the fields you need to add...*/) {
input = document.createElement("input");
input.type = "hidden";
input.name = /*...the field name...*/;
input.value = /*...the field value...*/;
form.appendChild(input);
}
document.body.appendChild(form);
form.submit();
})();
</script>
旁注:src="mywebsite.com/get_iframe"
不正确,URL 应为 //mywebsite.com/get_iframe
(协议(protocol)相关 URL)或者,如果页面是从该站点加载的,/get_iframe
或可能是 ./get_iframe
。
关于javascript - iframe 的 src 属性可以执行 POST 请求吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52027873/