iframe發送post請求


昨天踩了個坑,本來一個簡單的頁面能夠很快上線的,結果半天沒搞好。

需求是使用iframe,然后發送一個post請求去獲得響應頁面。平時使用iframe時,設定的src屬性是get請求方式。

一般有兩種方式:

  1. ajax使用post請求返回頁面,直接將返回的頁面數據放入iframe標簽中
  2. 結合form表單,利用form表單的post請求方式達到目的,我采用了這種方法

我參考html中iframe請求設定為post方式,采用了增加一個form表單的標簽,method設置為post,target設置與iframe的name屬性相同。

html代碼

<form
        id="ttsForm" target="iframe" method="post" action="url" >
</form>
<iframe name="iframe" frameborder="0" class="layadmin-iframe"></iframe>

js代碼

$('#ttsForm').attr('action', 'url');
$('#ttsForm').submit();

以上方式在第一次刷新頁面時,的確是發送了post請求,獲得了正確的響應。當在第二次點擊到這個iframe頁面的時候,卻發現不發送post請求,只有手動重新刷一次頁面才會發送請求。

在查找多種解決方案后, 參考了Stack Overflow上的一個回答,采用下面的方法終於解決了這個iframe的post請求問題,以下方法使得每次在切換到這個iframe中時都會發送post請求。

<form
        id="ttsForm" target="iframe" method="post" action="url" >
</form>
<iframe name="iframe" frameborder="0" class="layadmin-iframe"></iframe>

<script type="text/javascript">
    document.getElementById('ttsForm').submit();
</script>

本文參考:
[1] html中iframe請求設定為post方式
[2] Sending data through post method to an iframe


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM