jQuery Ajax 上傳檔案處理方式介紹(推薦)_jquery

來源:互聯網
上載者:User

AJAX 是一種與伺服器交換資料的技術,可以在補充在整個頁面的情況下更新網頁的一部分。

下面的表格列出了所有的 jQuery AJAX 方法:

jQuery Ajax在web應用開發中很常用,它主要包括有ajax,get,post,load,getscript等等這幾種常用無重新整理操作方法,接下來通過本文給大家介紹jquery ajax 上傳檔案處理方式。

FormData對象

XMLHttpRequest Level 2添加了一個新的介面FormData.利用FormData對象,我們可以通過JavaScript用一些索引值對來類比一系列表單控制項,我們還可以使用XMLHttpRequest的send()方法來非同步提交這個”表單”.比起普通的ajax,使用FormData的最大優點就是我們可以非同步上傳一個二進位檔案.

所有主流瀏覽器的較新版本都已經支援這個對象了,比如Chrome 7+、Firefox 4+、IE 10+、Opera 12+、Safari 5+。之前都是用原生js的XMLHttpRequest寫的請求

XMLHttpRequest方式

xhr.open("POST", uri, true);xhr.onreadystatechange = function() {if (xhr.readyState == 4 && xhr.status == 200) {// Handle response.alert(xhr.responseText); // handle response.}};fd.append('myFile', file);// Initiate a multipart/form-data uploadxhr.send(fd);

其實jquery的ajax也可以支援到的,關鍵是設定:processData 和 contentType 。

ajax方式

var formData = new FormData();var name = $("input").val();formData.append("file",$("#upload")[0].files[0]);formData.append("name",name);$.ajax({ url : Url, type : 'POST', data : formData, // 告訴jQuery不要去處理髮送的資料processData : false, // 告訴jQuery不要去設定Content-Type要求標頭contentType : false,beforeSend:function(){console.log("進行中,請稍候");},success : function(responseStr) { if(responseStr.status===0){console.log("成功"+responseStr);}else{console.log("失敗");}}, error : function(responseStr) { console.log("error");} });

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.