要是实在不知道要干什么,那就喝两杯思路就来了!

导航菜单

前端请求数据的几种写法

如果要将数据库中的内容展现在前端页面,我们就需要使用到类似像ajax这样的中间件。如今前端的发展走向可谓是高歌猛进,各种JS框架是层出不穷,当初原始的ajax也是被封装的应有尽有。现在我们就将觉的数据请求书写格式分别整理下来:

一、原始 JS 的书写格式 A

var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://www.snrthn.com/edu/api.php/shop', true);
xhr.onreadystatechange = function () {
	if(xhr.readyState === 4 && xhr.status === 200) {
		var res = JSON.parse(xhr.responseText);
		console.log (res);
	}
}
xhr.send();

二、原始 JS 的书写格式 B

var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://www.snrthn.com/edu/api.php/shop', true);
xhr.onload = function () {
	var res = JSON.parse(xhr.responseText);
	console.log (res);
}
xhr.send();

三、原始 jQuery 书写格式 A

<script src="https://www.snrthn.com/plugins/jquery-3.2.1.js"></script>
$.ajax({
	method: 'get',
	url: 'https://www.snrthn.com/edu/api.php/shop',
	success: function (res) {
		console.log (res);
	}
})

四、原始 jQuery 书写格式 B

<script src="https://www.snrthn.com/plugins/jquery-3.2.1.js"></script>
$.get({url: 'https://www.snrthn.com/edu/api.php/shop'}, function (res) {
	console.log (res);
})

五、axios 请求书写方式,它是一个基于 promise 的 http 库,可以用在浏览器和 node.js 中

<script src="https://www.snrthn.com/plugins/axios.js"></script>
axios ({
	method: 'get',
	url: 'https://www.snrthn.com/edu/api.php/shop',
	responseType: 'json'
}).then (function (res) {
	console.log (res);
}).catch (function (err) {
	console.log (err);
})

六、fetch 请求书写格式,它属于 JS 预置的一个方法,是 XMLHttpRequest 方法的替代品

fetch('https://www.snrthn.com/edu/api.php/shop', {method: 'GET'})
.then(function (data) {
	return data.json()
}).then(function (data) {
	console.log(data);
})

七、原生 JS 格式的 JSONP 请求方法

var script = document.createElement('script');
script.src = 'https://www.snrthn.com/jsonp?callback=jsonpCallback';
document.head.appendChild(script);
function jsonpCallback (res) {
	console.log(res);
}

无论选择哪一种书写方式,只要是最适合自己项目的就是最好的。需要强调的是 JSONP 项目中不常见,因为有 Access-Control-Allow-Origin 处理更加方便,而且 JSONP 还需要和后端约定好一些回调规则很麻烦,仅支持 GET 请求方式,之所以罗列出来是因为它确实是跨域请求的一种解决方案。除 JSONP 之后,在任何项目或任何框架中,可以选择前六种任意一种方式,程序不会有任何操作上的限制。

发表评论