2016-05-13 65 views
2

我試圖用POST和參數打開一個帶有iframe的網頁。 但做成後提交父頁面重新加載和URL沒開成的iframe:使用javascript將表單提交到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> 

回答

2

誰刷新頁面的錨標記。您可以使用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> 
+0

謝謝您分享您的知識! – deimos1975