[技术分享]自己封装了一个 Ajax 函数

isle24发布于2 个月前 • 144 次阅读

用法:AJAX(options:object)

AJAX({
    url:"./",//请求的地址
    method:"GET",//请求方式
    async:true,//是否异步
    complete:xhr=>console.log(xhr),//请求完成时的函数
    change:xhr=>console.info(xhr),//readyState改变时的函数
    data:{},//数据,如果是Object类型会自动转为JSON
    headers:{}//自定义header
});

封装的函数

window.AJAX = function (options = {}) {
		/*AJAX Sender*/
		var method, url, async, complete, change, headers, data;
		method = (options.method || 'GET').toUpperCase();
		url = options.url || '#';
		async = (typeof options.async == "boolean") ? options.async : true;
		complete = (typeof options.complete == "function") ? options.complete : function () { };
		change = (typeof options.change == "function") ? options.change : function () { };
		headers = options.headers || {};
		data = options.data;
		var xhr = window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
		xhr.open(method, url, async);
		if (typeof data == "object") {
			xhr.setRequestHeader("Content-Type", "application/json; Charset=UTF-8");
		}
		for (let header in headers) xhr.setRequestHeader(header, headers[header]);
		xhr.complete = complete;
		xhr.change = change;
		xhr.onreadystatechange = function () {
			if (xhr.readyState == 4) { this.complete(this); console.info("AJAX Sent!", this); }
			this.change(this);
		}
		xhr.send(data ? (typeof data == "object" ? JSON.stringify(data) : data) : undefined);
		return xhr;
	}
共收到 0 条回复