使用label的for屬性來取代js的event轉移,解決IE下“SCRIPT5: 拒絕訪問”的問題;
html代碼
| 代碼如下 |
複製代碼 |
<!DOCTYPE HTML> <html lang="en-US"> <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;" class="uploadform" 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即可。