Jquery:关于使用iframe将文件上传到服务器

时间:2016-02-04 18:32:38

标签: javascript jquery iframe file-upload

在下面的代码iframe用于将文件上传到服务器。看到代码并告诉我何时触发了iframe load事件?

<script type="text/javascript">
    $(document).ready(function () {

        $("#formsubmit").click(function () {

            var iframe = $('<iframe name="postiframe" id="postiframe" style="display: none"></iframe>');

            $("body").append(iframe);

            var form = $('#theuploadform');
            form.attr("action", "/upload.aspx");
            form.attr("method", "post");

            form.attr("encoding", "multipart/form-data");
            form.attr("enctype", "multipart/form-data");

            form.attr("target", "postiframe");
            form.attr("file", $('#userfile').val());
            form.submit();

            $("#postiframe").load(function () {
                iframeContents = this.contentWindow.document.body.innerHTML;
                $("#textarea").html(iframeContents);
            });

            return false;

        });

    });

</script>

代码来自jQuery iframe file upload

上面的代码动态创建iframe并追加到body并提交表单。以上代码文件如何通过iframe上传到服务器不清楚?

上述代码中文件上传和iframe之间的关系是什么?

当iframe加载时会调用吗?

$("#postiframe").load(function () {
                iframeContents = this.contentWindow.document.body.innerHTML;
                $("#textarea").html(iframeContents);
            });

参见代码

$("#postiframe").load(function () {
                iframeContents = this.contentWindow.document.body.innerHTML;
                $("#textarea").html(iframeContents);
            });

这一行正在做什么iframeContents = this.contentWindow.document.body.innerHTML; ?

为什么需要以下代码。

$("#postiframe").load(function () {
                iframeContents = this.contentWindow.document.body.innerHTML;
                $("#textarea").html(iframeContents);
            });

如果我们删除上面的代码,那么当我们尝试调用iframe的加载事件时,也会提交表单.......位混淆。

请详细讨论以正确理解。感谢

感谢

0 个答案:

没有答案