How can I use jQuery to dynamically load html into an iFrame?

心已入冬 提交于 2019-12-08 06:21:00

问题


I'm working on an iframe file uploader (so my file uploader appears to be ajax). I'm trying to take the form on my page and insert it into an iframe. Then I will submit the form inside the iframe. However, it isn't working. Here is my code:

jQuery:

function submitFile() {
    $(document).ready(function() {
        if ($('[name=files]').val() != "")
        {
            var fileForm = $('#attachFile').html();
            $('#emptyDiv').html('<iframe name="hiddenIframe" id="hiddenIFrame">'+fileForm+'</iframe>');
        }
    });
}

HTML:

<body>
    <div id="emptyDiv"></div>
    <div id="attachFile">
        <form action="my_file.php" method="post" enctype="multipart/form-data" id="uploadFile">
            <input type="file" name="files" id="files">
            <input id="fileUploadButton" type="submit" name="upload" value="Upload File" onclick="submitFile()">
        </form>
    </div>
</body>

This obviously isn't a complete solution, but I notice that after submitting the form I do manage to get the iframe inserted into the <div id="emptyDiv"> element. However, inside the iframe is the following code:

#document
<html>
    <head></head>
    <body></body>
</html>

But what I expect to see inside the iframe is the html contents located inside the form <div id="attachFile">. What am I missing?


回答1:


You don't try to copy the form to a hidden iframe, you submit the form to the hidden iframe. Set the target attribute (or property) of the form to the name of the iframe.

var fileForm = $('#attachFile form').prop('target', 'hiddenIframe');
$('#emptyDiv').html('<iframe name="hiddenIframe" id="hiddenIFrame"></iframe>');

or

<form action="my_file.php" method="post" enctype="multipart/form-data" id="uploadFile" target="hiddenIframe">
    <input type="file" name="files" id="files">
    <input id="fileUploadButton" type="submit" name="upload" value="Upload File" onclick="submitFile()">
</form>



回答2:


Try turning your HTML into a separate page and referencing it with the src attribute of the iframe.



来源:https://stackoverflow.com/questions/16380997/how-can-i-use-jquery-to-dynamically-load-html-into-an-iframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!