今天就跟大家聊聊有關怎么在PHP中使用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>
<h2>iframe模擬Ajax上傳文件</h2>
<h3 id="progress"></h3>
<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中使用iframe模擬Ajax上傳文件有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。