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

时间:2016-05-13 11:04:22

标签: 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>

1 个答案:

答案 0 :(得分:4)

刷新页面的人是锚标记。您可以使用event.preventDefault()

更改您的锚标记,添加事件参数。

<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>