本文實例為大家分享了php+ajax實現無刷新文件上傳的具體代碼,供大家參考,具體內容如下
文件上傳的表單格式
<form id="uploadform" enctype="multipart/form-data" name="uploadform" method="post" > <input id="fileToUpload" type="file" name="fileToUpload" class="uploadinput" > <input id="add_file" type="button" value="提交"></form>
AjaxFileUpload實現文件異步上傳效果更好,使用簡單:
 <!DOCTYPE html>  <html>    <head>      <title></title>      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">      <script type="text/javascript" src="http://www.phpddt.com/usr/themes/dddefault/jquery-1.4.2.min.js"></script>      <script type="text/javascript" src="ajaxfileupload.js"></script>    </head>  <script>  jQuery(function(){     $("#buttonUpload").click(function(){        //加載圖標       /* $("#loading").ajaxStart(function(){      $(this).show();     }).ajaxComplete(function(){      $(this).hide();     });*/     //上傳文件    $.ajaxFileUpload({      url:'upload.php',//處理圖片腳本      secureuri :false,      fileElementId :'fileToUpload',//file控件id      dataType : 'json',      success : function (data, status){        if(typeof(data.error) != 'undefined'){          if(data.error != ''){            alert(data.error);          }else{            alert(data.msg);          }        }      },      error: function(data, status, e){        alert(e);      }  })  return false;   })   })  </script>    <body>      <input id="fileToUpload" type="file" size="20" name="fileToUpload" class="input">      <button id="buttonUpload">上傳</button>    </body>  </html>上傳還可以傳遞參數:
 var data = { name: 'my name', description: 'short description' }     $.ajaxFileUpload({      url: 'upload.php',      secureuri: false,      data: data,      fileElementId: 'fileToUpload',      dataType: 'json',      success: function (data) {        alert(data.msg);      },      error: function (data) {        alert("error");      }    });主要參數說明:
	1、url表示處理文件上傳操作的文件路徑,可以測試URL是否能在瀏覽器中直接訪問,如上:upload.php
	2、fileElementId表示文件域ID,如上:fileToUpload
	3、secureuri是否啟用安全提交,默認為false
	4、dataType數據數據,一般選json,javascript的原生態
	5、success提交成功后處理函數
	6、error提交失敗處理函數
需要了解相關的錯誤提示
1、SyntaxError: missing ; before statement錯誤
如果出現這個錯誤就需要檢查url路徑是否可以訪問
2,SyntaxError: syntax error錯誤
如果出現這個錯誤就需要檢查處理提交操作的PHP文件是否存在語法錯誤
3、SyntaxError: invalid property id錯誤
如果出現這個錯誤就需要檢查屬性ID是否存在
4、SyntaxError: missing } in XML expression錯誤
如果出現這個錯誤就需要檢查文件域名稱是否一致或不存在
5、其它自定義錯誤
大家可使用變量$error直接打印的方法檢查各參數是否正確,比起上面這些無效的錯誤提示還是方便很多。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。
新聞熱點
疑難解答
圖片精選