文件结构图:

怎么在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>";//显示上传是否成功 
?>

本文参考链接:https://www.yisu.com/zixun/339865.html
评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

使用PHP怎么封装一个cURL工具类