1

現在のフォーム データを iframe に追加し、元のフォームではなく iframe 内でフォームを送信したいと考えています。以下はコードスニペットです

  <script> 
   $(document).ready(function() {
    $("#imageSubmit").click(function(e) {
     e.preventDefault(); 
     $("#wrapper iframe").remove();
     $("#wrapper").append("<iframe src=''>" + $("#imageForm").html()+"</iframe>");
     $("#wrapper iframe form").submit();
     $("#wrapper iframe").load(checkStatus);
    });
   });

   function checkStatus() {
    var status = $.parseJSON($("#wrapper iframe").html());
    if (status.success) {
     alert("File " + status.filename + " uploaded!");
    } else {
     alert("Fail!");
    }
   }
  </script>

<body>
  <div id="wrapper">
   <form name="imageForm" id="imageForm" action="SOMETHING">
    <input type="file" id="imageInput" />
    <input type="submit" id="imageSubmit" />
   </form>
  </div>
</body>  

ただし、現在のフォームの HTML を iframe に追加する代わりに、デコードされた HTML (この単語についてはすみません) を iframe に追加しています。これが私が得たiframe出力です:

    <iframe>
        &lt;input type="file" id="imageInput"&gt;
        &lt;input type="submit" id="imageSubmit"&gt; 
   </iframe>

提案してください。

4

2 に答える 2

2

iframe は、ウィンドウ内に別のドキュメントを作成するため、他の DOM 要素とは異なります。

もう 1 つの小さなトリックは、iframe がロードされるのを待つ必要があるため、loadイベントを使用iframeしてコンテンツを追加することです

iframe (同じドメインのみ) を使用するには、 を使用する必要がありますcontents()。その中に、 、、およびcontents()を含む新しいツリーがあります。documenthtmlheadbody

/* dummy src to avoid same domain restrictions in some browsers*/
var jsbinIframeSrc='http://jsbin.com/evoger/1';

var $iframe=$('<iframe src="'+jsbinIframeSrc+'" width="400px" height="300px"></iframe>'); 

$("#wrapper").append( $iframe);

var $form=$('#imageForm').on('submit', function(e){
    /* demo code to show that submit works when triggered inside iframe*/
    e.preventDefault();
    $(this).replaceWith('Form was submitted');
})



$iframe.on('load', function(){
    /* unbind "load" so doesn't add form again when submitted*/
    $iframe.off('load');
     /* insert form in iframe body*/
    $(this).contents().find('body').html($form);
    $form.submit();

})

デモ: http://jsbin.com/otobug/2/edit

API リファレンス: http://api.jquery.com/contents/

于 2013-01-20T00:39:25.953 に答える
0

ご返信ありがとうございます。私は以下の方法で行いました、チャンピオンのように機能します:

var iframe = "<iframe name='frame' id='frame' style='visibility:hidden' onload='onFrameLoad();'></iframe>";
$('wrapper').append(iframe);
$('#form').attr('target','frame');

function onFrameLoad(cur_form_number) {
.
.
}
于 2013-02-11T00:17:25.650 に答える