1. 程式人生 > >ajax 非同步提交資料、檔案和跨域提交的實現

ajax 非同步提交資料、檔案和跨域提交的實現

在網站中經常需要無重新整理提交資料,或者上傳圖片的情況,還有就是跨域提交的情況,現記錄下自己的總結,以待後續。

1.非同步提交資料:

function getAjax(){

$.ajax({
type : "get",
dataType : "json",
url : "/news/detail.html",
data : {

id : 1

},
complete : function() {
},
success : function(result) {
var data = result['success'];
alert(result['msg']);
},
});

}

2,非同步上傳圖片:

function uploadImg() {
var data = new FormData();
data.append('upfile', $('#uploadfile')[0].files[0]);
$.ajax({
url : '/upload/img',
type : 'POST',
dataType : "JSON",
data : data,
processData : false, // 告訴jQuery不要去處理髮送的資料  
contentType : false // 告訴jQuery不要去設定Content-Type請求頭  
}).done(function(data) {
var ret = data['state'];
});
}

3,跨域提交或查詢

function getAjax(){

$.ajax({
type : "get",
dataType : "jsonp",
url : "/news/detail.html",
data : {

id : 1

},
complete : function() {
},
success : function(result) {
var data = result['success'];
alert(result['msg']);
},
});

}

記錄開發過程中的點滴!