本文實例為大家分享了php+ajax實現無刷新文件上傳的具體代碼,供大家參考,具體內容如下
文件上傳的表單格式
1 | < form id = "uploadform" enctype = "multipart/form-data" name = "uploadform" method = "post" > |
2 | < input id = "fileToUpload" type = "file" name = "fileToUpload" class = "uploadinput" > |
3 | < input id = "add_file" type = "button" value = "提交" > |
AjaxFileUpload實現文件異步上傳效果更好,使用簡單:
05 | < meta http-equiv = "Content-Type" content = "text/html; charset=UTF-8" > |
07 | < script type = "text/javascript" src = "ajaxfileupload.js" ></ script > |
11 | $("#buttonUpload").click(function(){ |
13 | /* $("#loading").ajaxStart(function(){ |
15 | }).ajaxComplete(function(){ |
20 | url:'upload.php',//處理圖片腳本 |
22 | fileElementId :'fileToUpload',//file控件id |
24 | success : function (data, status){ |
25 | if(typeof(data.error) != 'undefined'){ |
33 | error: function(data, status, e){ |
42 | < input id = "fileToUpload" type = "file" size = "20" name = "fileToUpload" class = "input" > |
43 | < button id = "buttonUpload" >上傳</ button > |
上傳還可以傳遞參數:
01 | var data = { name: 'my name' , description: 'short description' } |
06 | fileElementId: 'fileToUpload' , |
08 | success: function (data) { |
12 | error: function (data) { |
主要參數說明:
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直接打印的方法檢查各參數是否正確,比起上面這些無效的錯誤提示還是方便很多。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。