【问题标题】:Append current form data to iframe将当前表单数据附加到 iframe
【发布时间】:2013-01-19 22:43:19
【问题描述】:

我想将当前表单数据附加到 iframe 并在 iframe 中提交表单而不是原始表单。下面是代码sn-p

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

请提出建议。

【问题讨论】:

    标签: jquery forms iframe append


    【解决方案1】:

    iframe 与其他 DOM 元素不同,因为它们在窗口中创建另一个文档。

    另一个小技巧是需要等待 iframe 加载,所以使用 iframeload 事件添加内容

    要使用 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/

    【讨论】:

      【解决方案2】:

      感谢您的回复。 我按照下面的方式做了,像冠军一样工作:

      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) {
      .
      .
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-01-28
        • 1970-01-01
        • 2013-04-18
        • 1970-01-01
        • 2011-11-27
        • 1970-01-01
        • 2013-06-03
        相关资源
        最近更新 更多