更新
问题不在于 iframe,问题在于发布 json 的 onsubmit 函数未提交表单。目标是动态创建一个 iframe,使用上面脚本标记的 json 内容使用表单发布重定向到另一个 URL。
原创
我在示例网站上有以下内容:
<script data-dashboard="true" type="application/json">
{
"title":"Serverless Identity"
}
</script>
<script type="text/javascript">
let dashboardConfiguration = document.querySelector("script[data-dashboard=\"true\"]");
if (dashboardConfiguration) {
let iframe = document.createElement("iframe");
let model = JSON.stringify(JSON.parse(dashboardConfiguration.innerHTML.trim()));
document.body.appendChild(iframe);
var doc = iframe.contentWindow.document;
doc.open()
doc.writeln(`<form id="form" action="https://localhost:44338/dashboard/" method="POST" target="_self"></form>`)
doc.close();
iframe.onload = () => {
let form = doc.getElementById("form");
form.addEventListener("submit", (e) => {
console.log(model);
e.preventDefault();
// construct an HTTP request
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action, true);
xhr.setRequestHeader('content-type', 'application/json; charset=UTF-8');
// send the collected data as JSON
xhr.send(model);
xhr.onloadend = function () {
// done
};
});
form.submit();
}
};
</script>
最佳答案
这不可能,
根据规范,当使用 form.submit()
时,任何 onsubmit 处理程序都不会触发。
我使用了一种不同的方法 og 发送一个普通的表单提交,使用表单编码值和一个隐藏字段中的空洞有效负载,并在服务器端反序列化它。
关于javascript - 动态 iframe 中的表单提交不会被触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55529598/