您当前的位置: 首页 > 学无止境 > 网站建设 网站首页网站建设
利用iframe模拟ajax上传文件demo
发布时间:2016-06-11 12:43:06编辑:雪饮阅读()
文件上传php中通常是通过post提交的方式提交至php脚本中进行处理的。但这样一来就要从表单页面跳转到php脚本页面。用户体验不够友好。那么能否用ajax上传呢?ajax一般只是传输变量而无法传递文件。但是我们可以想一个变通的方法。
实现思路:
表单页面中写一个隐藏的iframe,当表单提交时出发javascript事件使之提交至iframe中。当iframe中目标php脚本处理完毕后返回处理结果给iframe父级(表单页面),然后父级触发相应的javascript方法来提示用户上传的状态。
html:up.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript">
function ajaxup(){
//创建iframe框架并将表单提交到iframe框架中
var ifname='up'+Math.random();
$('<iframe name="'+ifname+'" width="0" height="0" frameBorder="0"></iframe>').appendTo($('body'));
$('form:first').attr('target',ifname);
//显示上传中的loading。。。
$('#progress').html('<img src="./timg.jpg">');
}
</script>
</head>
<body>
<h1>iframe模拟ajax文件上传</h1>
<form action="up.php" method="post" enctype="multipart/form-data" onsubmit="return ajaxup();">
<h2></h2>
<div id="progress"></div>
<input type="file" name="pic"/>
<input type="submit" value="上传"/>
</form>
</body>
</html>
php:up.php
<?php
//判断用户是否选择了文件
if(empty($_FILES)){
exit("no file");
}
//错误号为0即代表文件成功上传至服务器缓存目录中了。
$error=$_FILES['pic']['error']==0?'succ':'fail';
echo "<script>parent.document.getElementById('progress').innerHTML='$error'</script>";
?>
需要注意的是:如果上传文件超过2M(php.ini中默认文件上传的max为2M)则会在up.php中响应$_files为空。
源码:
关键字词:iframe,ajax,上传