ajaxsetup()其使用方法与ajax()并无区别,只是在其之后的ajax()不用再重复添加相同参数,节省了代码量。
附:api中关于jquery.ajaxsetup([options])的描述和jquery 代码:
描述:
设置 ajax 请求默认地址为 “/xmlhttp/”,禁止触发全局 ajax 事件,用 post 代替默认 get 方法。其后的 ajax 请求不再设置任何选项参数。
jquery 代码:
$.ajaxsetup({
url: "/xmlhttp/",
global: false,
type: "post"
});
$.ajax({ data: mydata });
function getcookie(name) {
var cookie = document.cookie
// console.log(cookie);
var arr = cookie.split("; ") //将字符串分割成数组
// console.log(arr);
for (var i = 0; i < arr.length; i++) {
var arr1 = arr[i].split("=")
if (arr1[0] == name) {
return unescape(arr1[1])
}
}
return "gg"
}
var token = getcookie("token")
$.ajaxsetup({
// contenttype:"application/x-www-form-urlencoded;charset=utf-8",
headers: {
token: token
},
//请求携带token必须设置以下参数
//--------------------------
crossdomain: true,
xhrfields: {
withcredentials: true // 要在这里设置 跨域设置cookie
},
//--------------------------
complete: function(xmlhttprequest, textstatus) {
// console.log(xmlhttprequest,textstatus)
if (xmlhttprequest.status == 401) {
window.location.href = "/"
}
}
})