AJAX 全称为 Asynchronous JavaScript And XML,就是异步的 JS 和 XML。
通过 AJAX 可以在浏览器中向服务器发送异步请求,最大的优势:无刷新获取数据。
AJAX 不是新的编程语言,而是一种将现有的标准组合在一起使用的新方式。
不重新加载页面的情况下,可以与服务器交换数据并更新部分网页内容的技术。
原生 ajax
- 创建 xmlhttprequest 对象
const xhr =new XMLHttpRequest()
- 使用 open 方法 创建ajax请求 open(’请求类型‘,’请求地址‘,是否异步(默认异步))
请求类型有 GET POST PUT PATCH DELETE 等,到底用哪个后台说了算,一般来说数据(比如商品列表)使用GET,传递数据(比如登录,评论)使用 POST
请求地址就是url 地址,后端提供的某个数据的接口地址
像后端请求用户列表信息
xhr.open('GET', 'https://jsonplaceholder.typicode.com/users', true)
- 使用 send 方法将创建好的请求发出
如果请求需要传回数据,就需要给send方法传参
xhr.send()
- onreadystatechange 监听整个请求的过程
readyState 状态
0: 请求未初始化
1: 服务器已连接
2:请求已接收
3:请求处理中
4:请求已完成,且响应已就绪
status Http状态码
responseText 响应的数据(后台返回的数据),是json字符串
目前后台数据交互的数据类型基本上都是 json 类型,也就是说,前端向后台传递数据用json ,后台给前端返回数据用 json
json 字符串转化对象型 JSON.parse(JSON字符串)
对象转化成json JSON.stringify(对象)
` xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
const users = JSON.parse(xhr.responseText)
const user = document.querySelector('.user')
console.log(user)
}
}`
发送一个登录的请求,需要向后台传递登录的数据
post 方法 https://cnodejs.org/api/v1/accesstoken
传递参数 accesstoken 值是String(用户的accessToken)
// post方法
const xhr = new XMLHttpRequest()
xhr.open('post', 'https://cnodejs.org/api/v1/accesstoken', true)
//传递数据一般 使用对象,然后转化成 json 再传递,比如这个 post 请求传递的参数,应该写成{accesstoken:值}对象的形式
//默认 原生的ajax 想要使用 json 数据传递给后台,是不可以的,需要设置请求的请求头使用setRequestHeader方法
xhr.setRequestHeader('Content-type', 'application/json')
xhr.send(JSON.stringify({ accesstoken: '261f3b58-da12-4164-80ea-b92ced0f6f47' }))
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(JSON.parse(xhr.responseText))
}
}
带参数的 get 请求
// get传参
const xhr = new XMLHttpRequest()
//当get 请求需要传递参数的时候可以直接将参数写在地址上,当成地址的查询部分
xhr.open('GET', 'https://cnodejs.org/api/v1/topics?tab=ask&page=1&limit=10')
xhr.send()
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(JSON.parse(xhr.responseText))
}
}
如果想发多个请求,改个名 const xhr2=new XmlHttpRequest()
jq Ajax
// 1. $.ajax({请求的配置})
$.ajax({
//地址
url: ('https://cnodejs.org/api/v1/accesstoken'),
//请求类型 默认 GET 须大写
type: 'POST',
//向后台传递的数据,直接写对象类型,无需写成json文件
//偶尔也可以用date传参
data: {
accesstoken: '261f3b58-da12-4164-80ea-b92ced0f6f47'
},
//请求成功的回调函数,请求成功后会自动执行,这个函数有个默认参数,这个参数就是请求返回结果,这个结果是对象类型(jq从json转过来
success(res) {
console.log(res)
},
//请求失败的回调函数,请求失败自动执行,err是错误信息
error(err) {
console.log(arr)
}
//发送给后台的数据类型设置,一般不用设置,我们传递数据使用对象即可
// contentType:
})
$.post(‘地址’,{参数},function(res){返回})
axios
cdn :<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.js"></script>
// axios
axios.get('https://cnodejs.org/api/v1/topics?tab=ask&&limit=10&&page=1').then((res) => {
//res 其实是axios 封装配置后的返回值, 也就是将后台返回的数据进行了封装,res.data 才是真正后台返回的数据
console.log(res.data) //Object { success: true, data: (10) […] }
}).catch((err) => {
console.log(err)
})
axios.post('https://cnodejs.org/api/v1/accesstoken', { accesstoken: '261f3b58-da12-4164-80ea-b92ced0f6f47' }).then((res) => {
console.log(res.data) //Object { success: true, loginname: "YangluFover", avatar_url: "https://avatars.githubusercontent.com/u/91188060?v=4&s=120", id: "616539fcfe0c51cb11aee455" }
}).catch((err) => {
console.log(err)
})
//axios删除
axios.delete("http://localhost:3008/todos/" + id);
原生 的 fatch()
fenth 方法传递俩个参数 1. url地址 2.配置项 {} , 获取请求回来的结果使用then放啊传递一个函数,该函数默认接受一个参数,并且在函数内返回这个 参数.jaon ,然后在使用一个then 方法,这个方法内的函数的参数就是后台返回的数据了。
get
fetch('https://cnodejs.org/api/v1/topics?tab=ask&page=1&limit=10', { method: 'GET' }).then((el) => {
return el.json()
}).then((res) => {
console.log(res)
})
post
fetch('https://cnodejs.org/api/v1/accesstoken', { method: 'POST', body: JSON.stringify({ accesstoken: '261f3b58-da12-4164-80ea-b92ced0f6f47' }), headers: { 'content-type': 'application/json' } }).then((el) => {
return el.json()
}).then((res) => {
console.log(res)
})
请求的跨域问题
- 两个地址传递数据的时候,浏览器有个同源测略,支持跨域请求,,如果需要,需要服务器处理
- cors 跨域资源共享
- 同源: url的 协议 域名(主机) 端口号相同
- 有些时候浏览器默认支持本地跨域,两个本地的url发生请求的时候
- 还有后台数据库已经处理完了跨域,前端随意请求
- 浏览器中出现 Cross-origin 报错,则大概率是同源问题