鍍金池/ 問答/HTML/ ajax 如何統(tǒng)一設(shè)置headers攜帶參數(shù)?

ajax 如何統(tǒng)一設(shè)置headers攜帶參數(shù)?

原生的ajax, 如何全局配置每一個ajax請求的headers都帶上某寫些個參數(shù)?
不用每一個ajax都調(diào)用 setRequestHeaders方法來設(shè)置?

回答
編輯回答
尐懶貓

自己封裝一個方法

function ajax(config, callbackS, callbackF) {
    // 設(shè)置常用的默認(rèn)值
    var url = config.url || '/';
    var method = config.method || 'GET';
    var async = config.async === undefined ? true : config.async;
    var contentType = config.contentType || 'application/x-www-form-urlencoded';
    var header = config.header || {};
    var data = config.data;

    // 創(chuàng)建XMLHttpRequest對象
    var xhr = new XMLHttpRequest();

    // 初始化請求
    xhr.open(method, url, async);

    // 設(shè)置header的默認(rèn)值
    xhr.setRequestHeader('Content-Type', value);

    // 設(shè)置其它header
    for (var item in header) {
        xhr.setRequestHeader(item, header[item]);
    }

    // 發(fā)送請求
    xhr.send(data);

    // 處理響應(yīng)
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            if (xhr.status == 200) {
                callbackS && callbackS(xhr.responseText);
            }
            else {
                callbackF && callbackF(xhr.status);
            }
        }
    }
}
2018年1月15日 03:54