1.ajax和axios的区别
1.区别:
1.axios是一个基于Promise的HTTP库,而ajax是对原生XHR的封装;
2.ajax技术实现了局部数据的刷新,而axios实现了对ajax的封装。
2. 目前所学写法上的区别:
Ajax
概念: ajax (全称: Asynchronous JavaScript And XML) 是异步的JavaScript和xml等多种技术的组合,用于快速创建动态页面,实现无刷新更新数据。它的核心对象是XMLHttpRequest(XHR),对原生的XHR进行封装。
通俗理解:在网页中利用 XMLHttpRequest 对象和服务器进行数据交互的方式,就是Ajax
原生写法:
1.使用xhr发起get请求
步骤:
- 创建xhr对象
- 调用xhr.open()函数
- 调用xhr.send()函数
- 监听xhr.onreadystatechage事件
// 1.创建 XHR 对象
const xhr = new XMLHttpRequest()
// 2.调用open函数
xhr.open('get', 'http://www.liulongbin.top:3006/api/getbooks')
// 3.调用send函数
xhr.send()
// 4.监听 onreadystatechange
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status === 200){
//获取服务器端响应给我们的数据
console.log(xhr.responseText)
}
}
2.使用xhr发起post请求
// 1.创建 xhr 对象
const xhr = new XMLHttpRequest()
// 2.调用xhr.open()
xhr.open('post', 'http://www.liulongbin.top:3006/api/addbook')
// !3.设置Content-Type属性(固定写法)
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
// 4.调用send方法
xhr.send('bookname=猪猪侠&author=66号技师&publisher=楼下舞指仙境')
// 5.监听事件
xhr.onreadystatechange = function () {
// xhr对象的status如果为200,那就代表着当前请求接口成功; readyState如果为4,代表着当前请求的阶段是完成通信
if (xhr.readyState === 4 & xhr.status === 200) {
console.log(xhr.responseText)
}
}