javascript - 使用 javascript 将表单提交到 iframe 目标

标签 javascript html iframe

我正在尝试使用 POST 和参数将网页打开到 iframe 中。 但是,当提交时,父页面会重新加载,并且 URL 不会在 iframe 中打开:

<head>
    <title>iframe Example</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <style>
    iframe {
        display: block;       /* iframes are inline by default */
        background: #000;
        border: none;         /* Reset default border */
        height: 90vh;        /* Viewport-relative units */
        width: 90vw;
    }
    </style>
    </head>
    <body>
    <form id="myForm" method="post" action= "http://127.0.0.1/myWeb" target="myIframe">
    <input type = "hidden" name="param1" value="param1value">
    <input type = "hidden" name="param2" value= "param1value">
    </form>
     <a href="" onClick="postLogin();" >Send to iframe</a><br />
    <script laguaje="javascript">
        function postLogin() {
            var form = document.getElementById("myForm");
            form.submit();
        }
    </script>
     <iframe  src="" name="myIframe" id="myIframe">
       <p>iframes are not supported by your browser.</p>
     </iframe>
    </body>
    </html>

最佳答案

谁刷新页面就是 anchor 标签。您可以使用event.preventDefault() .

更改 anchor 标记添加事件参数。

<a href="" onClick="postLogin(event);" >Send to iframe</a>

并且在Javascript函数中postLogin添加preventDefault()事件方法:

    function postLogin(event) {
        var form = document.getElementById("myForm");
        form.submit();

        event.preventDefault();
    }

编辑:

或者您可以使用<button>没有 postLogin函数而不是 <a> .

    <form id="myForm" method="post" action= "http://127.0.0.1/myWeb" target="myIframe">
      <input type = "hidden" name="param1" value="param1value">
      <input type = "hidden" name="param2" value= "param1value">
      <button type="submit">Send to iframe</button>
    </form>

关于javascript - 使用 javascript 将表单提交到 iframe 目标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37208408/

相关文章:

javascript - 通过 Arduino 控制将 JavaScript 命令推送到网站

javascript - 倒数计时器css分析

javascript - 返回上一页时自动播放音频文件

node.js - 尝试渲染 iframe : ancestor violates the following Content Security Policy directive: "frame-ancestors ' none'"

javascript - iOS 上的 IFrame 高度问题(移动版 safari)

javascript - 如何使 HTML5 Canvas 图案 fillstyle 随绘制对象一起移动?

javascript - 元素的 readyState 是 HAVE_NOTHING

javascript - 如何从Grails外部化属性文件中的Javascript文件中读取属性

html - Windows 7 中的 VS 2012 HTML5 JS 项目

javascript - 网页 : How to center right div for all screen sizes