本文實例講述了PHP+iframe模擬Ajax上傳文件功能。分享給大家供大家參考,具體如下:
在xmlhttprequest level 1
中,Ajax是不能夠上傳文件的,因為js不能操作本地文件,但是市場上有一些Ajax異步上傳文件的插件,是怎么完成的呢?答案:可以使用iframe
模擬Ajax上傳文件。接下來博主將使用iframe來模擬Ajax來上傳文件。
首先看一下效果圖:
文件結構圖:
09-iframe-upload.html文件:
頁面中有一個表單,表單中有一個上傳文件按鈕和提交按鈕,點擊提交按鈕執行ajaxUpload函數,然后動態創建iframe標簽,讓其不可見,最后設置表單的target屬性指向iframe。
<!DOCTYPE html><html><head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>iframe模擬Ajax上傳文件</title> <link rel="stylesheet" href=""></head><script src="http://libs.baidu.com/jquery/1.7.2/jquery.min.js"></script><script> /** * 文件上傳 * @return bool 是否提交表單 * 1、捕捉表單提交的動作 * 2、動態創建iframe標簽,然其不可見 * 3、設置表單的target屬性指向iframe */ function ajaxUpload(){ var iframeName = 'upload'+Math.random();//給iframe取名 $('<iframe name='+iframeName+' width="0" height="0" frameborder="0"></iframe>').appendTo($('body'));//動態創建iframe $('form:first').attr('target',iframeName);//設置form的target屬性 $('#progress').html('<img src="progress.jpg"/>');//顯示上傳是否成功 //return false; }</script><body> <h1>iframe模擬Ajax上傳文件</h1> <h2 id="progress"></h2> <form action="09-iframe-upload.php" method="post" enctype="multipart/form-data" onsubmit="return ajaxUpload();"> <p><input type="file" name="pic"/></p> <p><input type="submit" value="提交" /></p> </form></body></html>
09-iframe-upload.php文件:
首先延時3秒,為了能看到加載的圖片,然后判斷是否有上傳文件,然后返回一段Js代碼,這段js是在頁面中顯示是否上傳成功
<?php/** * iframe模擬Ajax上傳文件 * @author webbc */sleep(3);//延時3秒if(empty($_FILES)){ echo 'no file';}$error = $_FILES['pic']['error'] == 0?'succ':'fail';//判斷上傳是否成功echo "<script>parent.document.getElementById('progress').innerHTML='$error'</script>";//顯示上傳是否成功?>
希望本文所述對大家PHP程序設計有所幫助。
新聞熱點
疑難解答
圖片精選