??在使用原生Ajax發(fā)送一個(gè)請(qǐng)求時(shí),過(guò)程多少有點(diǎn)繁瑣,jQuery中對(duì)于Ajax請(qǐng)求有它自己的封裝好的函數(shù),使用起來(lái)分方便。
?在jQuery中有專(zhuān)門(mén)的Ajax封裝,具體參照JQuery-Ajax參考手冊(cè)網(wǎng)址
這里用一段練習(xí)代碼展示下使用方法:
//使用要引入jQuery文件 <script src="../jq/jquery-1.12.4.min.js"></script>
$.ajax({
url:"http://localhost:3000/users",
type:"get",
dataType:"json",
data:{"id":3},
beforeSend:function(xhr){
console.log("before send");
},
success:function(data){
console.log(data);
},
error:function(){
console.log("請(qǐng)求error");
},
complete:function(xhr){
console.log("complete");
console.log(xhr);
}
})
關(guān)于jQuery中$.ajax() 的幾個(gè)參數(shù)介紹:
url:請(qǐng)求地址;
type:請(qǐng)求方法,默認(rèn)為”get";
dataType:服務(wù)端響應(yīng)數(shù)據(jù)類(lèi)型;
contentType:請(qǐng)求體內(nèi)容的類(lèi)型,默認(rèn)“application/x-www-form-urlencode”;
data:需要傳輸?shù)椒?wù)器的數(shù)據(jù),如果是get則通過(guò)、url傳遞;post則通過(guò)請(qǐng)求體傳遞;
timeout:請(qǐng)求超時(shí)時(shí)間;
beforeSend:請(qǐng)求發(fā)起之前觸發(fā);
success:請(qǐng)求成功之后觸發(fā)(響應(yīng)狀態(tài)碼200);
error:請(qǐng)求失敗觸發(fā);
complete:請(qǐng)求完成后觸發(fā)(不管成功與否)
jQuery中其他請(qǐng)求:
-
$.get(),獲取數(shù)據(jù)
jQuery中g(shù)et請(qǐng)求快捷方法:$.get(url,data,callback回調(diào)函數(shù),返回的數(shù)據(jù)格式datatype);
//發(fā)送 get請(qǐng)求 $.get("http://localhost:3000/liuyan",{"content":"hi"}, function(data){ console.log(data); });
-
$.post,添加數(shù)據(jù)
$.post(url,data,callback)
//發(fā)送post請(qǐng)求 $.post(url,data,callback,datatype) $.post("http://localhost:3000/liuyan",{"content":"ajax","userId":1}, function(data){ console.log(data); })
-
$.put,更改數(shù)據(jù)
//put 請(qǐng)求 $.ajax({ url:"http://localhost:3000/liuyan/5",//需要在地址上標(biāo)出改的主鍵 type:"put", dataType:"json", data:{"content":"put 請(qǐng)求啊"},//改的內(nèi)容 success:function(data){ console.log(data) } })
-
$delete,刪除數(shù)據(jù)
//刪除數(shù)據(jù) delete請(qǐng)求 $.ajax({ url:"http://localhost:3000/liuyan/6", type:"delete", success:function(data){ console.log(data); } })//刪除數(shù)據(jù) delete請(qǐng)求 $.ajax({ url:"http://localhost:3000/liuyan/6", type:"delete", success:function(data){ console.log(data); } }) -
$.ajaxSetup() 方法設(shè)置全局 AJAX 默認(rèn)選項(xiàng)。
$.ajaxSetup({ url:"https://localhost:3000", type:post }); $.ajax({ data:{"name":"value"} }); 等等還有很多方法,可以參考jquery-Ajax手冊(cè)。