温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在PHP中使用iframe模拟Ajax上传文件

发布时间:2021-04-14 17:12:54 来源:亿速云 阅读:118 作者:Leah 栏目:开发技术

今天就跟大家聊聊有关怎么在PHP中使用iframe模拟Ajax上传文件,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

文件结构图:

怎么在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上传文件有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI