AJAX
一. AJAX概念
1 概念
Asynchronous Javascript And Xml (异步javascript和xml)
**异步的js和xml技术**(这里的xml是一种数据格式, 现在更多的使用json数据格式)
2 作用
执行异步HTTP(Ajax)请求 !!!!!!<br /> 可以让我们轻松的实现网页和服务器之间的**数据交互**<br /> 可以在不刷新整个页面的基础上,更新部分网页内容(局部刷新)<br /> 一般作为前后端分离中**请求数据的解决方案**
3 同步和异步
同步: 同一时间只能做一件事. 阻塞式
服务端在处理时, 客户端只能等待
异步: 同一时间可以处理多件事, 非阻塞
4 使用场景
- 创建XMLHttpRequest对象
- 设置请求方式
- 发送请求
获取响应数据, 处理返回结果
<body>
<script>
//1,创建ajax对象
var xhr = new XMLHttpRequest()
//2,设置请求方式和url
xhr.open('get','./test.txt')//请求的是本地的文件
//3,发送请求
xhr.send()
//4,设置回调函数(获取请求后的数据)
xhr.onload = function(){
console.log(xhr.responseText);//打印服务端响应过来的的文本数据
}
console.log('这是同步代码');
</script>
</body>
1 发送get请求
<body>
<script>
//1,创建ajax对象
var xhr = new XMLHttpRequest()
//2,设置请求方式和url
xhr.open('get','http://localhost:3000/users/1')//请求的是服务端的json数据
//3,发送请求
xhr.send()
//4,设置回调函数(获取请求后的数据)
xhr.onload = function(){
console.log(xhr.responseText);//打印服务端响应过来的的json数据
console.log(typeof(xhr.responseText));//string类型
//调用js的内置对象JSON的parse方法将json字符串转成js对象
const obj = JSON.parse(xhr.responseText)
console.log(obj);//{id: 1, name: 'xiaoming', age: 20}
console.log(typeof obj);//object类型
}
console.log('这是同步代码');
</script>
</body>
2 发送post请求
<body>
<button id="btn">新增</button>
<script>
const btn = document.querySelector("#btn")
btn.addEventListener('click',function(){
//1,创建ajax对象
var xhr = new XMLHttpRequest()
//2,设置请求方式和url
xhr.open('post','http://localhost:3000/users')//请求的是服务端的json数据
//3,发送请求
//创建一个js对象
const user = {name:'王五',age:25}
//设置请求头,告诉服务器,我发送的是json数据
xhr.setRequestHeader('content-type','application/json')
xhr.send(JSON.stringify(user))
//4,设置回调函数(获取请求后的数据)
xhr.onload = function(){
console.log(xhr.status);//获取响应的状态
console.log(xhr.responseText);//获取响应回来的文本
}
console.log('这是同步代码');
})
</script>
</body>
3 发送put请求
<body>
<button id="btn">修改</button>
<script>
const btn = document.querySelector("#btn")
btn.addEventListener('click',function(){
//1,创建ajax对象
var xhr = new XMLHttpRequest()
//2,设置请求方式和url
xhr.open('put','http://localhost:3000/users/1')//请求的是服务端的json数据
//3,发送请求
//创建一个js对象
const user = {name:'王五',age:25}
//设置请求头,告诉服务器,我发送的是json数据
xhr.setRequestHeader('content-type','application/json')
xhr.send(JSON.stringify(user))
//4,设置回调函数(获取请求后的数据)
xhr.onload = function(){
console.log(xhr.status);//获取响应的状态
console.log(xhr.responseText);//获取响应回来的文本
}
console.log('这是同步代码');
})
</script>
</body>
4 发送delete请求
<body>
<button id="btn">删除</button>
<script>
const btn = document.querySelector("#btn")
btn.addEventListener('click',function(){
//1,创建ajax对象
var xhr = new XMLHttpRequest()
//2,设置请求方式和url
xhr.open('delete','http://localhost:3000/users/1')//请求的是服务端的json数据
//3,发送请求
xhr.send()
//4,设置回调函数(获取请求后的数据)
xhr.onload = function(){
console.log(xhr.status);//获取响应的状态
console.log(xhr.responseText);//获取响应回来的文本
}
console.log('这是同步代码');
})
</script>
</body>
三. jQuery中的Ajax
1 $.ajax()方法
jQuery提供了方便的方式, 封装了ajax请求的方法
语法
$.ajax({
url: '请求地址',
type: 'GET/POST',// 请求类型
data: {}, // 请求参数,发送到服务器的数据
dataType: 'json', // 返回的数据格式
success: function (res) {}, // 成功的回调
error: function(err) {} // 出错的回调
})
示例 get请求
<body>
<script>
/**
$.ajax({
url: '请求地址',
type: 'GET/POST',// 请求类型
data: {}, // 请求参数,发送到服务器的数据
dataType: 'json', // 返回的数据格式
success: function (res) {}, // 成功的回调
error: function(err) {} // 出错的回调
})
*/
$.ajax({
url:'http://localhost:3000/users',
type:'get',
data:{id:2},//如果data省略,返回的就是所有的数据
dataType:'text',//默认返回的是js对象(因为jquery自动帮你把返回的json字符串转成js对象了),如果就想获取json字符串,就写text
success:function(res){
console.log(res);
console.log(typeof res);
}
})
</script>
</body>
示例 post请求
<body>
<button>新增</button>
<script>
$('button').click(function(){
$.ajax({
url:'http://localhost:3000/users',
type:'post',//请求方式
data:{name:'前妻',age:27},
dataType:'json',//响应过来数据的格式
success:function(res){
console.log(res);
console.log(typeof res);
}
})
})
</script>
</body>
2 $.get()方法
$.get()是发送get请求的简写方式
语法
格式:
$get(url, [data], [callback], [type])
url:待载入页面的URL地址
data:待发送 Key/value 参数。
callback:载入成功时回调函数。
type:返回内容格式,xml, html, script, json, text, _default。
$.get("url", {params}, callback)
示例
$.get('http://localhost:3000/users', {id: 1}, function(res) {
console.log(res)
})
3 $.post()方法
$.post()是发送post请求的简写方式
语法
$.post("url", {params}, callback)
示例
$.post('http://localhost:3000/users', {name: 'xxp', age: 1}, function(res) {
console.log(res)
})
四. 跨域请求
1 什么是跨域请求
当从一个域A向另一个域B发送请求时, 就叫做跨域请求
这里的域指的是这样的一个概念:协议 + 域名 + 端口号均相同,那么就是同一个域.
如:
http://localhost:8080
请求https://localhost:8080
是跨域请求, 协议不同http://localhost:8080
请求http://www.baidu.com
是跨域请求, 域名不同http://localhost:8080
请求http://localhost:3000/users
是跨域请求, 端口不同2 跨域请求的问题
由于浏览器同源策略的限制, 浏览器是不允许发送跨域请求的.
但是, 我们做前后端分离, 前端和后端通常是一在同一个域.如
前端运行在http://localhost:5500
后端运行在http://localhost:3000
3 模拟跨域请求
后端 ```javascript // 引入http核心模块 var http = require(‘http’)
// 引入url核心模块 var url = require(‘url’)
// 创建web服务器 var server = http.createServer()
// 处理请求 server.on(‘request’, (req, res) => { // 设置响应头 res.writeHead(‘200’, { ‘content-type’: ‘text/html;charset=utf-8’, })
// 分析路由 var data = url.parse(req.url, true) var pathname = data.pathname var query = data.query
if (pathname == ‘/‘ || pathname == ‘/index’) { // 处理get请求 if (req.method == ‘GET’) { // 打印在后端控制台 console.log(query) // 返回给浏览器 res.end(query.username) } } else if (pathname == ‘/users’) { res.end(JSON.stringify({ name: ‘xxp’, age: 1 })) } else { res.writeHead(‘404’) res.end(‘Not Found’) } })
// 监听3000端口 server.listen(3000)
console.log(‘server is running on localhost:3000’)
前端
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$.ajax({
url: 'http://localhost:3000/users',
data: { id: 1 },
dataType: 'json',
success: function (res) {
console.log(res)
},
})
</script>
</body>
</html>
演示
4 如何解决跨域问题
a 在服务端设置响应头
目前, 最主流的方式是CORS, 通过在服务端设置响应头, 允许跨域请求
跨源资源共享 Cross-Origin Resource Sharing(CORS) 是一个新的 W3C 标准,它新增的一组HTTP首部字段,允许服务端其声明哪些源站有权限访问哪些资源。换言之,它允许浏览器向声明了 CORS 的跨域服务器,发出 XMLHttpReuest 请求,从而克服 Ajax 只能同源使用的限制
配置上非常简单, 只需要在后端设置响应头即可
// 设置响应头
res.writeHead('200', {
'Access-Control-Allow-Origin': '*',
})
b 在服务端开启CORS
在服务端开启CORS, 在服务端回复的响应头中, 加入特殊的头信息, 允许浏览器发送跨域请求
在后端安装cors中间件
https://www.npmjs.com/package/cors
npm i cors
在app.js中导入cors中间件
const cors = require('cors')
全局注册cors()中间件
app.use(cors())
解决方法: 其实也是在服务端的响应头中,设置
res.append('Access-Control-Allow-Origin','*')