Javascript利用iframe架構實現檔案上傳

來源:互聯網
上載者:User

   html

 代碼如下  

<form name="multiform" id="multiform" action="multi-form-submit.php" method="POST" enctype="multipart/form-data">
    姓名: <input type="text" name="name"  value="Ravi"/> <br/>
    年齡 :<input type="text" name="age"  value="1" /> <br/>
    頭像 :<input type="file" name="photo" /><br/>
    <input  type="button" id="multi-post" value="提交"></input>

</form>
<div id="multi-msg"></div>

  js

 代碼如下  

<script>
$(document).ready(function()
{

//擷取返回的document
function getDoc(frame) {
     var doc = null;

     // IE8 cascading access check
     try {
         if (frame.contentWindow) {
             doc = frame.contentWindow.document;
         }
     } catch(err) {
     }

     if (doc) { // successful getting content
         return doc;
     }

     try { // simply checking may throw in ie8 under ssl or mismatched protocol
         doc = frame.contentDocument ? frame.contentDocument : frame.document;
     } catch(err) {
         // last attempt
         doc = frame.document;
     }
     return doc;
 }

function postToIframe(formObj,callback){
    $("#multi-msg").html("<img src='loading.gif'/>");
    var formURL = formObj.attr("action");

    //產生隨機id
    var  iframeId = 'unique' + (new Date().getTime());

    //產生空白的iframe
    var iframe = $('<iframe src="javascript:false;" name="'+iframeId+'" />');

    //掩藏iframe
    iframe.hide();

    //給iframe設定target
    formObj.attr('target',iframeId);

    //添加iframe 到 body
    iframe.appendTo('body');
    iframe.load(function(e){
        var doc = getDoc(iframe[0]);
        var docRoot = doc.body ? doc.body : doc.documentElement;
        var data = docRoot.innerHTML;
        //回呼函數 用於接收 iframe 中的傳回值
        callback.call(this,data);
    });

}

$("body").on('submit',"#multiform",function(e)
    {    //提交資料到Iframe中並返回資料
        postToIframe($(this),function(data){
            alert(data);
        });
    });

$("body").on('click',"#multi-post",function()
{
    $("#multiform").submit();
});

}
);
</script>

php

<?php
    echo "FILES =".json_encode($_FILES)."<br><br>";
    echo "POST =".json_encode($_POST)."<br>";
?>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.