javascript - 动态 iframe 中的表单提交不会被触发
问题描述
更新
问题不在于 iframe,问题在于发布 json 的 onsubmit 函数未提交表单。目标是动态创建一个 iframe,该 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 处理程序时都不会触发。
我使用了一种不同的方法,即使用表单编码值发送普通表单提交,其中一个隐藏字段中的孔有效负载,并在服务器端对其进行反序列化。
推荐阅读
- iis - Blazor - 在 IIS windows server 2012 中运行时出现内部服务器错误
- python - 如何在循环分组的熊猫数据帧时获取第一行或最后一行
- javascript - Threejs中带有PointerLockControls的单向SpotLight
- unicode - 影响字母排序的不可见 Unicode 字符
- angular - “AbstractControl”类型上不存在属性“控件”。角 12
- reactjs - 如何更改 DatePicker 的日期格式 - Material-UI (React)
- arrays - 使用 VBA 解析 JSON 字符串并遍历字典中的所有元素
- qt - 隐藏 PathView 中的第一个或最后一个项目
- unit-testing - 如何在墨水中设置调用者!合约单元测试功能?
- c++ - 类型的参数与类型错误的参数不兼容