首页 > 解决方案 > 动态 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>

我也尝试了onsubmit与正常提交相同的结果。 在此处输入图像描述

标签: javascript

解决方案


这是不可能的,

根据规范,使用form.submit()任何 onsubmit 处理程序时都不会触发。

我使用了一种不同的方法,即使用表单编码值发送普通表单提交,其中一个隐藏字段中的孔有效负载,并在服务器端对其进行反序列化。


推荐阅读