1、原生ajax
1.1、Ajax简介
Ajax全程Asynchronous JavaScript And XML,即异步的js和XML
通过Ajax可以在浏览器中向服务器发送异步请求,最大优势:不需要刷星就可以获得数据
Ajax不是编程语言,而是一种将现有的标准组合在一起使用的新方式。
1.2、XMl简介
XML 可扩展标记语言。
被设计用来传输和储存数据
XML和HTML类似,不同的是HTML中都是预定义标签,而XML中没有预定义标签,全是自定义标签,用来表示一些数据
现在用json
1.3、Ajax优缺点
- 优点:
- 可以不用刷新页面就能与服务器端通信
- 允许根据与用户事件来更新部分页面内容。
- 缺点:
- 无浏览记录,不能回退
- 存在跨域问题(默认不可跨域)
- SEO不友好(搜索引擎搜索不到)
1.4、Ajax的使用
1.4.1、Ajax请求的基本操作
- GET请求
<body>
<button>点击发送请求</button>
<div id="result"></div>
<script>
//获取button元素
const but = document.getElementsByTagName('button')[0];
//绑定事件
but.onclick = function(){
//1.创建对象
const xhr = new XMLHttpRequest();
const result = document.getElementById('result')
//2.初始化 设置请求方法和url
xhr.open('GET','http://localhost:8000/server');
//3.发送
xhr.send();
//4.事件绑定 处理服务端返回的结果
//on 当什么时
//readystate 是xhr对象中的属性,表示状态0(初始值) 1(open方法调用完毕) 2(send方法调用完毕) 3(服务端返回部分的结果) 4(服务端返回的所有结果)
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
//判断响应状态码 200 404 403 ...
//2xx 表示成功
if(xhr.status >= 200 && xhr.status < 300){
//处理响应结果 行 头 空行 体
console.log(xhr.status);//状态码
console.log(xhr.statusText);//状态字符串
console.log(xhr.getAllResponseHeaders);//所有响应头
console.log(xhr.response);//响应体
result.innerHTML = xhr.response
}
}
}
}
</script>
</body>
</html>
//1.引入express
// const { response } = require('express');
const express = require('express');
//2.创建应用对象
const app = express();
//3。创建路由规则
//request 是对请求报文的封装
//response 是对响应报文的封装
app.get('/server',(request,response)=>{
//设置响应头 设置允许跨域
response.setHeader('Access-Control-Allow-Origin','*');
//设置响应体
response.send('这是用express服务器框架创建的node服务器')
});
//4.监听端口启动服务
app.listen(8000,()=>{
console.log("服务器创建成功");
})
设置url参数(url后面接 " ? " 参数名和值,多个参数用 " & " 连接)
xhr.open('GET','http://localhost:8000/server?a=123&b=321&c=231');
- POST请求
result.addEventListener("mouseover",function(){
//1.创建对象
const xhr = new XMLHttpRequest();
//2.初始化 设置类型与 URl
xhr.open('POST','http://localhost:8000/server');
//3.发送
xhr.send();
//4.事件绑定
xhr.onreadystatechange = function(){
//判断
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status < 300){
result.innerHTML = xhr.response;
}
}
}
})
//设置post响应
app.post('/server',(request,response)=>{
//设置响应头 设置允许跨域
response.setHeader('Access-Control-Allow-Origin','*');
//设置响应体
response.send('这是用express服务器框架创建的node服务器,返回post响应')
});
设置参数:
xhr.send('a=123&b=321&c=231');//无格式要求,但是需要在服务器端中有对应的处理方式
设置响应头
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
1.4.2 服务端响应json数据
//.html
<script>
//绑定dom元素
const result = document.getElementById('result')
//绑定键盘按下事件
window.onkeydown = function(){
//发送请求
const xhr = new<