萬盛學電腦網

 萬盛學電腦網 >> 腳本專題 >> javascript >> Javascript利用iframe框架實現文件上傳

Javascript利用iframe框架實現文件上傳

   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>";
?>

copyright © 萬盛學電腦網 all rights reserved