一、AJAX简介
简介:不刷新页面情况下更新页面内容。
查看
控制台Network中可以快捷方便查看请求及响应信息。
优缺点
优点:不刷新页面更新数据。
缺点:页面没有历史回退;不利于SEO。
历史:
信息格式:XML【自定义标签】 ==》JSON
AJAX历程:原生AJAX【XMLHttpRequest】 ==》JQuery中AJAX ==》axios
举例:
1、掘金的页面,滚动到底部才会加载下一屏。就是滚动到底部触发事件,事件中发送AJAX请求请求下一屏数据。
2、京东【下图】,只有鼠标hover上去才会加载对应的功能,就是AJAX。
![在这里插入图片描述](https://img-blog.csdnimg.cn/607474b5be1042adada53b89cf54f7a9.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5YmN56uv5bCP55Sc,size_10,color_FFFFFF,t_70,g_se,x_16)
![在这里插入图片描述](https://img-blog.csdnimg.cn/10104183d27e45c6b62e352de8afa96e.png)
二、原生AJAX
前端代码
btnGet.onclick = function() {
let xhr = new XMLHttpRequest()
xhr.timeout = 2000
xhr.ontimeout = function() {
alert('请求超时!')
}
xhr.onerror = function() {
alert('网络异常!')
}
xhr.open('GET', 'http://localhost:8000/serverOne?a=100&t=' + Date.now())
xhr.send()
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.response)
}
}
}
btnPost.onclick = function() {
let xhr2 = new XMLHttpRequest()
xhr2.open('POST', 'http://localhost:8001/serverTwo')
xhr2.send('a=100&b=jia')
xhr2.onreadystatechange = function() {
if (xhr2.readyState === 4 && xhr2.status === 200) {
}
}
}
celBtn.onclick = function() {
xhr.abort()
}
后端代码【借助node与express实现】【下面的代码段就是express官网的,很简单,看官网即可】
const express = require('express')
const app = express()
const port = 8001
app.post('/serverTwo', (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*')
res.setHeader('Access-Control-Allow-Headers', '*')
res.send('Hello World!!!')
})
app.listen(port, () => {
console.log(`正在监听 http://localhost:${port}`)
})
三、Jquery的Ajax
$('button').eq(0).click(function() {
$.get('地址',{id:123,psw:123},function(data)=>{......},'json')
$.post('地址',{传参},function(data)=>{......},'json')
$.ajax({
url:'',
type:'GET',
data:{},
dataType:'json'
timeout:2000,
success:funcion(data){.....}
error:function(){......}
})
})
四、Ajax的进化——Axios
axios.get('地址',{params:{..参数...}})
axios.post('地址',{username: 'admin',pasword: 'admin'},{params:{..参数...}})
axios({
method:'POST',
url:'',
data:{},
params:{},
headers:{}
}).then(res=>{....})