最基礎的調用
$.ajax('add.php',{
type:'post',
success:function(res){
//這裏res拿到的只是響應體
}
})
dataType用於設置響應體的類型,一旦設置dataType選項,就不在關心服務端響應的content-type了
success函數中的res會自動根據服務端響應的content-type自動轉換爲對象
$.ajax({
url:'add.php',
type:'get',
data:{id:1,name:'zx'},
dataType:'json',
success:function(res){
}
})
$.ajax({
url:'add.php',
type:'get',
beforeSend:function(xhr){
// 在所有發送請求的操作之前執行(open send)
console.log(xhr)
},
success:function(res){
// 只有請求成功(狀態碼爲200) 纔會執行這個函數
console.log(res)
},
error:function(xhr){
// 只有請求不正常纔會執行(狀態碼不爲200)
console.log(xhr)
},
complete:function(xhr){
// 不管是成功還是失敗都是完成,都會執行這個complete函數
console.log(xhr)
}
})
get、getJSON、post
$.get('add.php',{di:1},function(res){
console.log(res)
})
$.post('add.php',{di:1},function(res){
console.log(res)
})
$.getJSON('add.php',function (res) {
console.log(res)
})
全局ajax事件處理函數
只要有ajax的請求發生就會自動調用函數
$(document).ajaxStart(function () {
// 只要有ajax請求發生 就會執行
})
$(document).ajaxStop(function(){
// 只要要ajax請求結束,就會執行
})