Ajax請求頭設定Content-type
阿新 • • 發佈:2019-02-08
一:原生ajax請求頭
使用setRequestHeader函式:
先呼叫open方法開啟一個url:
xhr.open("post", "/save");
設定資料格式:
1.傳送json格式資料:
xhr.setRequestHeader("Content-type","application/json; charset=utf-8");
2.傳送表單資料:
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
3.傳送純文字(預設值):
xhr.setRequestHeader ("Content-type", "text/plain; charset=utf-8");
4.傳送html文字:
xhr.setRequestHeader("Content-type", "text/html; charset=utf-8");
5.編碼可帶可不帶:
// 不帶字元編碼寫法
xhr.setRequestHeader("Content-type", "application/json");
6.值對大小寫不敏感:
xhr.setRequestHeader("Content-type","Application/JSON; charset=utf-8");
二:Jquery中ajax設定請求頭
全域性的:
// 這個是全域性的,所有的ajax請求都會加上這個請求頭
$(document).ajaxSend(function (event, xhr) {
xhr.setRequestHeader("custom-header", "custom-info") ; // 增加一個自定義請求頭
});
區域性的:
- 第一種
$('xxx').ajax({
//...
beforeSend:function(jqXHR,options){
jqXHR.setRequestHeader("custom-header", "custom-info" ) ; // 增加一個自定義請求頭
}
//...
}) ;
- 第二種
$('xxx').ajax({
//...
headers:{
"Referer": "http://www.365mini.com" // 有些瀏覽器不允許修改該請求頭
,"User-Agent": "newLine" // 有些瀏覽器不允許修改該請求頭
,"X-Power": "newLine"
,"Accept-Language": "en-US"
}
//...
}) ;