Ajax封装

简版GET请求

同步请求

const type = 'GET';
const url = '/api/login?name=test&&pswd=123';
const isAsync = false;
const xhr = new XMLHttpRequest();
xhr.open(type, url, isAsync);
xhr.send(null);
if (xhr.status == 200) {
    console.log(xhr.responseText); //成功结果
} else {
    console.log(xhr.response); //失败结果
}

异步请求

const type = 'GET';
const url = '/api/login?name=test&&pswd=123';
const isAsync = true;
const xhr = new XMLHttpRequest();
xhr.open(type, url, isAsync);
xhr.send(null);
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        if (xhr.status == 200) {
            console.log(xhr.responseText); //成功结果
        } else {
            console.log(xhr.response); //失败结果
        }
    }
};

简版PSOT请求

同步请求

const type = 'POST';
const url = '/api/login';
const isAsync = false;
const data = { name: 'test', pswd: '123' };
const xhr = new XMLHttpRequest();
xhr.open(type, url , isAsync);
xhr.setRequestHeader('Content-type', 'application/json');
xhr.send(JSON.stringify(data));
if (xhr.status == 200) {
   console.log(xhr.responseText); //成功结果
} else {
    console.log(xhr.response); //失败结果
}

异步请求

const type = 'POST';
const url = '/api/login';
const isAsync = false;
const data = { name: 'test', pswd: '123' };
const xhr = new XMLHttpRequest();
xhr.open(type, url, isAsync);
xhr.setRequestHeader('Content-type', 'application/json');
xhr.send(JSON.stringify(data));
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        if (xhr.status == 200) {
            console.log(xhr.responseText); //成功结果
        } else {
            console.log(xhr.response); //失败结果
        }
    }
};

服务器端响应结果XHR 对象属性说明

属性名说明
responseText作为响应主体被返回的文本
responseXML如果响应主体内容类型是"text/xml"或"application/xml", 则返回包含响应数据的 XMLDOM 文档
status响应的 HTTP 状态
statusTextHTTP 状态的说明

异步调用触发 readystatechange事件readyState 属性说明

状态说明
0未初始化尚未调用 open()方法
1启动已经调用 open()方法,但尚未调用 send()方法
2发送已经调用 send()方法,但尚未接受响应
3接收已经接收到部分响应数据
4完成已经接收到全部响应数据,而且可以使用

HTTP状态码

HTTP 状态码状态字符串说明
200OK服务器成功返回了页面
400BadRequest语法错误导致服务器不识别
401Unauthorized请求需要用户认证
404Notfound指定的 URL 在服务器上找不到
500InternalServer Error服务器遇到意外错误,无法完成请求
503ServiceUnavailable由于服务器过载或维护导致无法完成请求

封装ajax方法一

function ajax(obj){
	var xhr = createXHR();
	obj.method = obj.method || 'get'; //默认以get方式发送
	obj.async = obj.async || true; //默认为异步请求
	obj.url += '?rang='+ Math.random();
	obj.data = params(obj.data);
	if(obj.method === '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 === 'post'){
		xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		xhr.send(obj.data);
	}else{
		xhr.send(null);
	}
	if(obj.async === false){
		callback();
	}
	function callback(){
		if(xhr.status == 200){
			obj.success(xhr.responseText);
		}else{
			obj.error(xhr);
		}
	}

	function createXHR(){
		if(typeof XMLHttpRequest != 'undefined'){
			return new XMLHttpRequest();
		}else if(typeof ActiveXObject != 'undefined'){
			var version = [
				'MSXML2.XMLHttp.6.0',
				'MSXML2.XMLHttp.3.0',
				'MSXML2.XMLHttp'
			];
			for(var i=0; i<version.length; i++){
				try{
					return new ActiveXObject(version[i]);
				}catch(e){
					//跳过
				}
			}
		}else{
			throw new Error('您的系统或浏览器不支持XHR');
		}
	}

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

//调用ajax
addEvent(document,'click',function(){
	ajax({
		url: 'demo.php',
		data: {
			name: 'Le&e',
			age: 100
		},
		success: function(text){
			alert(text);
		},
		error: function(xhr){
			alert('获取数据错误,错误代号:' + xhr.status + '错误信息:' + xhr.statusText);
		}
	});
})


//demo.php
<?php
	header('charset=utf-8');
	//echo Date('Y-m-d H:i:s');
	print_r($_GET);
	/*if($_GET['name'] == 'Lee'){
		echo '李合飞';
	}*/
	print_r($_POST);
	/*if($_POST['name'] == 'Lee'){
		echo '李合飞';
	}*/
?>

封装ajax方法二

function ajax(obj){
	obj.type = obj.type || 'get';
	obj.async = obj.async || true;
	obj.url += '?t=' + new Date().getTime();
	obj.data = params(obj.data);
	if(obj.type === 'get'){
		obj.url += obj.url.indexOf('?') == -1 ? '?' + obj.data : '&' + obj.data;
	}
	var xhr = null;
	if(window.XMLHttpRequest){
		xhr = new XMLHttpRequest();
	}else{
		xhr = new ActiveXObject('Microsoft.XMLHTTP');
	}
	xhr.open(obj.type, obj.url, obj.async);
	if(obj.type === 'get'){
		xhr.send(null);
	}else{
		xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		xhr.send(obj.data);
	}
	if(obj.async === true){
		xhr.onreadystatechange = function(){
			if(xhr.readyState == 4){
				callback();
			}
		};
	}else{
		callback();
	}

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

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


ajax({
	url: 'ajax.txt',
	data: {
		user: 'lihefei',
		password: 888888
	},
	success: function(text){
		alert(text);
	}
});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值