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

AJAX简单封装

发布时间:2020-12-15 21:08:31 所属栏目:百科 来源:网络整理
导读:ajax 简单封装, 支持 get post function params(data) {var arr = [];for(var i in data) {arr.push(encodeURIComponent(i) + '=' + encodeURIComponent(data[i]));}return arr.join('');}function ajax(obj) {var xhr = new XMLHttpRequest();obj.data = p

ajax 简单封装, 支持 get post

function params(data) {
	var arr = [];
	for(var i in data) {
		arr.push(encodeURIComponent(i) + '=' + encodeURIComponent(data[i]));
	}
	return arr.join('&');

}

function ajax(obj) {
	var xhr = new XMLHttpRequest();
	obj.data = params(obj.data);
	if(obj.method.toUpperCase() === 'GET') obj.url += obj.url.indexOf('?') == -1 ? '?' + obj.data : "&" + obj.data;
	if(obj.async === true) {
		xhr.onreadystatechange = function() {
			if(xhr.readyState == 4) {
				callback();
			}
		}
	};

	xhr.open(obj.method,obj.url,obj.async);

	if(obj.method.toUpperCase() === 'POST') {
		xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		xhr.send(obj.data);
	} else {
		xhr.send(null);
	}

	function callback() {
		if(xhr.status == 200) {
			obj.success(xhr.responseText);
		} else {
			alert('error');
		}
	}
}

div.onclick = function() {

	ajax({
		url: 'http://localhost:8080/webApi/list.do',method: 'post',data: {
			'pageCount': '10','pageNow': '1'
		},success: function(text) {
			var jsonData = JSON.parse(text);
			alert(text);
		},async: true
	});

};

(编辑:李大同)

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

    推荐文章
      热点阅读