- setting参数 headers
$.ajax({ headers: { Accept: "application/json; charset=utf-8" }, type: "get", success: function (data) { } });
- beforeSend设置header
$.ajax({ type: "GET", url: "default.do", beforeSend: function(request) { request.setRequestHeader("Test", "Chenxizhang"); }, success: function(result) { alert(result); } });
- $.ajaxSetup()全局设置Header请求头
// 设置请求默认值 $.ajaxSetup({ beforeSend: function (xhr) { //可以设置自定义标头 // 将token塞进Header里 xhr.setRequestHeader('Authorization', 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9'); xhr.setRequestHeader('Content-Type', 'application/json'); // application/x-www-form-urlencoded }, complete: function (xhr) { // 设置登陆拦截 if (xhr.responseJSON.code == "error_unauth") { console.log("没有登录!"); layer.msg("没有登录!"); // location.href="login.html"; } else { console.log("已经登录!"); } }, });
- 或
// 设置请求默认值 $.ajaxSetup({ headers: { // 默认添加请求头 "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9" , "Content-Type": "application/json" } , complete: function (xhr) { // 设置登陆拦截 if (xhr.responseJSON.code == "error_unauth") { console.log("没有登录!"); layer.msg("没有登录!"); // location.href="login.html"; } else { console.log("已经登录!"); } }, });