php+iframe实现无刷新上传文件例子
上传文件用得最多的是ajax了,现在这里我们可以使用iframe 模仿了,下面php入门小伙伴就来为各位同学整理一个frame实现无刷新上传文件例子,希望能帮助到各位朋友哦。
使用label的for属性来取代js的event转移,解决IE下"SCRIPT5: 拒绝访问"的问题;
html代码
<!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title></title> <script src="//code.jquery.com/jquery-1.11.0.min.js"></script> <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script> <script> // 当前上传对象 var _current = null; // 上传回调方法 function onUploadSuccess(info){ // 控制台调试,可能是因为console没定义导致IE无法使用此功能 typeof console.dir!=='undefined' && console.dir(info); // 上传成功 if(typeof info.status!=='undefined' && typeof info.path!=='undefined' && info.status==1 && info.path!=''){ // 改变图片src,实现实时预览 if(_current.find('img').size()>0) _current.find('img:eq(0)').prop('src', info.path); else _current.html('<img src="'+info.path+'" width="100%" height="100%" />'); // 返回 return; } // 上传失败则提示错误信息 alert(info.info); // 返回 return; } $(function(){ $('label[for]').click(function(){ _current = $(this); $('.uploadform')[0].reset(); }); $('.uploadform input:file').change(function(){ $(this).parent().submit(); }); }); </script> </head> <body> <label for="photo1" style="border:1px solid #CCC; padding:2px; width:120px; height:80px; display:block;"></label> <label for="photo1" style="border:1px solid #CCC; padding:2px; width:120px; height:80px; display:block;"></label> <form style="display:none;" action="{:U('upload?callback=window.parent.onUploadSuccess')}" method="post" enctype="multipart/form-data" target="uploadiframe"> <input type="file" name="photo1" id="photo1" /> <iframe style="display:none;" name="uploadiframe"></iframe> </form> </body> </html>
php处理程序
<?php $retval = array('status'=>0, 'info'=>'', 'path'=>''); if(/*upload success*/){ $retval['status'] = 1; $retval['path'] = 'somepath'; }else{ $retval['info'] = 'someerror'; } echo "<script>{$_GET['callback']}(".json_encode($retval).");</script>"; exit;
简单总结:这个其实很简单在表单中我们action设置为上传php的模板文件,然后我们再在表单target 打开方式设置为iframe的name即可。
本文地址:http://www.phprm.com/code/65114.html
转载随意,但请附上文章地址:-)