溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

怎么在PHP中使用iframe模擬Ajax上傳文件

發(fā)布時(shí)間:2021-04-14 17:12:54 來源:億速云 閱讀:121 作者:Leah 欄目:開發(fā)技術(shù)

今天就跟大家聊聊有關(guān)怎么在PHP中使用iframe模擬Ajax上傳文件,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

文件結(jié)構(gòu)圖:

怎么在PHP中使用iframe模擬Ajax上傳文件

09-iframe-upload.html文件:

頁面中有一個(gè)表單,表單中有一個(gè)上傳文件按鈕和提交按鈕,點(diǎn)擊提交按鈕執(zhí)行ajaxUpload函數(shù),然后動(dòng)態(tài)創(chuàng)建iframe標(biāo)簽,讓其不可見,最后設(shè)置表單的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、捕捉表單提交的動(dòng)作
   * 2、動(dòng)態(tài)創(chuàng)建iframe標(biāo)簽,然其不可見
   * 3、設(shè)置表單的target屬性指向iframe
   */
  function ajaxUpload(){
    var iframeName = 'upload'+Math.random();//給iframe取名
    $('<iframe name='+iframeName+' width="0" height="0" frameborder="0"></iframe>').appendTo($('body'));//動(dòng)態(tài)創(chuàng)建iframe
    $('form:first').attr('target',iframeName);//設(shè)置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文件:

首先延時(shí)3秒,為了能看到加載的圖片,然后判斷是否有上傳文件,然后返回一段Js代碼,這段js是在頁面中顯示是否上傳成功

<?php
/**
 * iframe模擬Ajax上傳文件
 * @author webbc
 */
sleep(3);//延時(shí)3秒
if(empty($_FILES)){
  echo 'no file';
}
$error = $_FILES['pic']['error'] == 0?'succ':'fail';//判斷上傳是否成功
echo "<script>parent.document.getElementById('progress').innerHTML='$error'</script>";//顯示上傳是否成功
?>

看完上述內(nèi)容,你們對(duì)怎么在PHP中使用iframe模擬Ajax上傳文件有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI