【记录】AJAX

Asyncchronous JavaScript And XML
异步的JS和XML。


优缺点

优点
(1)无需刷新页面与服务端进行通信。
(2)允许你根据用户事件来更新部分页面内容。
缺点
(1)没有浏览历史,不能回退。
(2)存在同源跨域问题。
(3)SEO不友好。

基本操作

let xhr = null;
btns[0].onclick = function(){
	xhr = newXMLHttpRequest();
	xhr.open('POST', 'http://127.0.0.1:8000/server');
	//针对get请求ie缓存问题
	xhr.open('GET', 'http://127.0.0.1:8000/ie?t='+Date.now());
	//设置请求头内容
	xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	//设置相应体格式(自动)
	xhr.responseType = 'json';
	//超时
	xhr.timeout = 2000;
	xhr.ontimeout = function(){
		alert('网络异常,请稍后重试!');
	};
	//网络异常
	xhr.onerror = function(){
		alert('您的网络似乎出现了一点问题。');
	};
	xhr.send('a=1&b=2');
	//readystate表示状态。
	//0表示未初始化,1表示open方法调用完毕,2表示send方法调用完毕,3表示服务端发送部分数据,4表示服务端返回了所有结果。
	xhr.onreadystatechange = function(){
		if(xhr.readystate === 4){
			//判断响应状态码
			if(xhr.status >= 200 && xhr.state < 300){
				console.log(xhr.status);//状态码
				console.log(xhr.statusText);//状态字符串
				console.log(xhr.getAllResponseHeaders());//所有的响应头
				console.log(xhr.response);//响应体
				//设置响应体格式(手动)
				//console.log(JSON.parse(xhr.response));
				...
			}else{
				...
			}
		}
	};
}

//取消ajax请求
btns[1].onclick = function(){
	xhr.abort();
}

jQuery发送AJAX请求

$('button').eq(0).click(function(){
	$.get('http://127.0.0.1:8000/jquery-server', {a:100, b:200}, function(data){
		console.log(data);
	}, 'json');
	//最后一个参数设置响应体格式。 
	
	$.post('http://127.0.0.1:8000/jquery-server', {a:100, b:200}, function(data){
		console.log(data);
	}, 'json');
	
	//通用
	$.ajax({
		url: 'http://127.0.0.1:8000/jquery-server',
		type: 'GET',
		headers: {
			c: 1
		},
		data: {
			a: 100,
			b: 200
		},
		dataType: 'json', 
		success: function(data){
			console.log(data);
		},
		timeout: 2000,
		error: function(){
			console.log('error'); 
		}
	});
});


Axios发送AJAX请求

艾克谢尔斯

btns[0].onclick = function(){
	axios.defaults.baseURL = 'http://127.0.0.1:8000';
	axios.get('/axios-server',{
		headers: {
			c: 1
		},
		params: {
			id: 100,
			vip: 7
		}
	}).then(()=>{
		...
	});
		
	axios.post('/axios-server',{id: 100, vip: 7},{
		headers: {
			c: 1
		}
	}).then(()=>{
		...
	});
	
	//通用方法
	axios({
		url: '/axios-server',
		method: 'POST',
		headers: {
			c: 1
		},
		params: {
			id: 100,
			vip: 7
		},
		data: {
			usrname: 'a'
		}
	}).then(res=>{
		console.log(res.status);//状态码
		console.log(res.statusText);//状态字符串
		console.log(res.headers);//所有的响应头
		console.log(res.data);//响应体
	});
};

fetch函数发送AJAX请求

btn.onclick = function(){
	fetch('http://127.0.0.1:8000:/fetch-server',{
		method: 'POST',
		headers: {
			c: 1
		},
		body: 'usrname=admin&psw=admin'
	}).then(res=>{
		return res.text();
		//return res.json();
	}).then(res=>{
		console.log(res);
	});
};

同源策略

Same-Origin Policy
由Netscape公司提出的浏览器的一种安全策略。
同源

  • 网页地址和服务器的协议、域名、端口号必须完全相同。

跨域

  • 违背同源策略。

跨域解决方案

1、JSONP

JSON with Padding

  • 前后端一起处理。
  • 只支持get请求。
  • 利用天生具有跨域能力的script标签(img、link、iframe等也具有)来发送请求。
function jsonp({url, params, callback}){
    return new Promise((resolve, reject)=>{
        let script = document.createElement('script');
        window[callback] = function(data){
            resolve(data);
            document.body.removeChild(script);
        }
        params = {...params, callback};
        let arrs = [];
        for(let key in params){
            arrs.push(`${key}=${params[key]}`);
        }
        script.src = `${url}?${arrs.join('&')}`;
        document.body.appendChild(script);
    });
}

jsonp({
    url: '',
    params: {
        wd: 'aaa'
    },
    callback: 'show'
}).then(data=>{
    ...
})


2、CORS

Cross-Origin Resource Sharing
跨域资源共享

  • 只需后端处理。
  • 支持get请求和post请求。
  • 真正的解决跨域。
  • 通过服务端设置响应头(Access-Control-Allow-Origin)来开启。该属性表示哪些域名可以访问资源;设为*表示所有网站都可以访问资源。

3、代理服务器

浏览器和服务器之间通过ajax请求进行通信。服务器之间直接通过http进行通信,不存在跨域问题。

  • 浏览器<=>代理服务器<=>服务器

nginx反向代理

  • 正向代理:目标服务器不知道,代理服务器替客户端请求。
  • 反向代理:客户端不知道,代理服务器替客户端请求。
  • nginx反向代理说明
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值