jQuery.ajax 全局设置Header请求头

5,073 阅读1分钟

方法1、使用$.ajaxSetup() 方法

该函数用于更改 jQueryAJAX 请求的默认设置选项。之后执行的所有 AJAX 请求,如果对应的选项参数没有设置,将使用更改后的默认设置。

// 设置请求默认值
$.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("已经登录!");
        }
    },
});

方法2、封装$.ajax,后面全局调用这个封装的方法

 /**
     * POST 请求
     */
    post: function (options, succback, errback) {
        if (!options.url) {
            alert('请求错误,url不可为空!');
            return false;
        }
        options.type = 'POST';
        options.timeout = options.timeout || 5000;
        options.async = options.async || true;
        options.cache = options.cache || false;
        options.dataType = options.dataType || 'json';
        options.contentType = options.contentType || 'application/x-www-form-urlencoded';
        options.data = options.data || '';
        $.ajax({
            url: options.url,
            type: options.type,
            timeout: options.timeout,
            async: options.async,
            cache: options.cache,
            dataType: options.dataType,
            data: options.data,
            contentType: options.contentType, // 发送数据到服务器时所使用的内容类型。默认是:"application/x-www-form-urlencoded"
          	headers: {
                "Authorization" : "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9",
                "Powered-By" : "wowo-mini"
            },
            success: function (result, status, xhr) {
                // 成功回调
                if (!!succback) {
                    succback(result);
                }
            },
            error: function (xhr, status, error) {
                // 错误回调
                if (!!errback) {
                    errback(error);
                }
            }
        });
    },

调用示例:

Util.post({
  	url: Util.ctx + 'fileupload/uploadFileAjax',
  	data: formData
}, function (res) {
  	layer.close(index);
  	if (0 === res.code) {

    	Message.success(res.message, 1000);
  } else {
    	Message.error(res.message, 1000);
  }
}, function (error) {
  	layer.close(index);
 		Message.error("服务器异常!" + error, 1000);
});