加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ajax的js插件封装

发布时间:2020-12-16 03:34:52 所属栏目:百科 来源:网络整理
导读:最近回顾一下ajax,ajax使用并不难,下面对ajax简单封装,方便以后使用: window.onload = function() {new Ajax({method: 'GET',//传输方式url: 'data_handle.php',//数据文件data: 'name=dalinage=23',//发送数据,可选succee: function(data) {//返回数据

最近回顾一下ajax,ajax使用并不难,下面对ajax简单封装,方便以后使用:

window.onload = function() {
	new Ajax({
		method: 'GET',//传输方式
		url: 'data_handle.php',//数据文件
		data: 'name=dalin&age=23',//发送数据,可选
		succee: function(data) {//返回数据为字符串,需要转换为json格式
			alert(data);
		},fail: function(error) {
			alert('无法获取数据' + error);
		}
	});
};

(function() {
	function Ajax(o) {
		this.config = o;
		var that = this;
		this.XHR = new XMLHttpRequest();
		this.requestFn();
		this.XHR.onreadystatechange = function() {
			that.stateFn();
		}
	}
	Ajax.prototype.requestFn = function() {
		if(this.config.data && this.config.method.toLowerCase() == 'get') {
			var url = this.config['url'] + '?' + this.config.data;
		} else {
			var url = this.config['url'] + '?a=' + Math.random();
		}
		this.XHR.open(this.config.method,url,true);
		if(this.config.data && this.config.method.toLowerCase() == 'post') {
			this.XHR.setRequestHeader('Content-type','application/x-www-form-urlencoded');
			this.XHR.send(this.config.data);
		} else {
			this.XHR.send(null);
		}
	}
	Ajax.prototype.stateFn = function() {
		if(this.XHR.readyState == 4) {
			if(this.XHR.status == 200) {
				return this.config.succee(this.XHR.responseText);
			} else {
				return this.config.fail(this.XHR.statusText);
			}
		}
	}
	window.Ajax=Ajax;
})();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读