AJAX

一. AJAX概念

1 概念

Asynchronous Javascript And Xml (异步javascript和xml)

  1. **异步的jsxml技术**(这里的xml是一种数据格式, 现在更多的使用json数据格式)

2 作用

  1. 执行异步HTTP(Ajax)请求 !!!!!!<br /> 可以让我们轻松的实现网页和服务器之间的**数据交互**<br /> 可以在不刷新整个页面的基础上,更新部分网页内容(局部刷新)<br /> 一般作为前后端分离中**请求数据的解决方案**

3 同步和异步

同步: 同一时间只能做一件事. 阻塞式

  1. 服务端在处理时, 客户端只能等待

异步: 同一时间可以处理多件事, 非阻塞

4 使用场景

  • baidu地图
  • baidu联想搜索
  • 接口编程

    二. 原生AJAX的使用

    在浏览器中, 可以通过创建XMLHttpRequest对象来使用ajax.一般步骤如下
  1. 创建XMLHttpRequest对象
  2. 设置请求方式
  3. 发送请求
  4. 获取响应数据, 处理返回结果

    1. <body>
    2. <script>
    3. //1,创建ajax对象
    4. var xhr = new XMLHttpRequest()
    5. //2,设置请求方式和url
    6. xhr.open('get','./test.txt')//请求的是本地的文件
    7. //3,发送请求
    8. xhr.send()
    9. //4,设置回调函数(获取请求后的数据)
    10. xhr.onload = function(){
    11. console.log(xhr.responseText);//打印服务端响应过来的的文本数据
    12. }
    13. console.log('这是同步代码');
    14. </script>
    15. </body>

    1 发送get请求

    1. <body>
    2. <script>
    3. //1,创建ajax对象
    4. var xhr = new XMLHttpRequest()
    5. //2,设置请求方式和url
    6. xhr.open('get','http://localhost:3000/users/1')//请求的是服务端的json数据
    7. //3,发送请求
    8. xhr.send()
    9. //4,设置回调函数(获取请求后的数据)
    10. xhr.onload = function(){
    11. console.log(xhr.responseText);//打印服务端响应过来的的json数据
    12. console.log(typeof(xhr.responseText));//string类型
    13. //调用js的内置对象JSON的parse方法将json字符串转成js对象
    14. const obj = JSON.parse(xhr.responseText)
    15. console.log(obj);//{id: 1, name: 'xiaoming', age: 20}
    16. console.log(typeof obj);//object类型
    17. }
    18. console.log('这是同步代码');
    19. </script>
    20. </body>

    2 发送post请求

    1. <body>
    2. <button id="btn">新增</button>
    3. <script>
    4. const btn = document.querySelector("#btn")
    5. btn.addEventListener('click',function(){
    6. //1,创建ajax对象
    7. var xhr = new XMLHttpRequest()
    8. //2,设置请求方式和url
    9. xhr.open('post','http://localhost:3000/users')//请求的是服务端的json数据
    10. //3,发送请求
    11. //创建一个js对象
    12. const user = {name:'王五',age:25}
    13. //设置请求头,告诉服务器,我发送的是json数据
    14. xhr.setRequestHeader('content-type','application/json')
    15. xhr.send(JSON.stringify(user))
    16. //4,设置回调函数(获取请求后的数据)
    17. xhr.onload = function(){
    18. console.log(xhr.status);//获取响应的状态
    19. console.log(xhr.responseText);//获取响应回来的文本
    20. }
    21. console.log('这是同步代码');
    22. })
    23. </script>
    24. </body>

    3 发送put请求

    1. <body>
    2. <button id="btn">修改</button>
    3. <script>
    4. const btn = document.querySelector("#btn")
    5. btn.addEventListener('click',function(){
    6. //1,创建ajax对象
    7. var xhr = new XMLHttpRequest()
    8. //2,设置请求方式和url
    9. xhr.open('put','http://localhost:3000/users/1')//请求的是服务端的json数据
    10. //3,发送请求
    11. //创建一个js对象
    12. const user = {name:'王五',age:25}
    13. //设置请求头,告诉服务器,我发送的是json数据
    14. xhr.setRequestHeader('content-type','application/json')
    15. xhr.send(JSON.stringify(user))
    16. //4,设置回调函数(获取请求后的数据)
    17. xhr.onload = function(){
    18. console.log(xhr.status);//获取响应的状态
    19. console.log(xhr.responseText);//获取响应回来的文本
    20. }
    21. console.log('这是同步代码');
    22. })
    23. </script>
    24. </body>

    4 发送delete请求

    1. <body>
    2. <button id="btn">删除</button>
    3. <script>
    4. const btn = document.querySelector("#btn")
    5. btn.addEventListener('click',function(){
    6. //1,创建ajax对象
    7. var xhr = new XMLHttpRequest()
    8. //2,设置请求方式和url
    9. xhr.open('delete','http://localhost:3000/users/1')//请求的是服务端的json数据
    10. //3,发送请求
    11. xhr.send()
    12. //4,设置回调函数(获取请求后的数据)
    13. xhr.onload = function(){
    14. console.log(xhr.status);//获取响应的状态
    15. console.log(xhr.responseText);//获取响应回来的文本
    16. }
    17. console.log('这是同步代码');
    18. })
    19. </script>
    20. </body>

    三. jQuery中的Ajax

    1 $.ajax()方法

    jQuery提供了方便的方式, 封装了ajax请求的方法

    语法

  1. $.ajax({
  2. url: '请求地址',
  3. type: 'GET/POST',// 请求类型
  4. data: {}, // 请求参数,发送到服务器的数据
  5. dataType: 'json', // 返回的数据格式
  6. success: function (res) {}, // 成功的回调
  7. error: function(err) {} // 出错的回调
  8. })

示例 get请求

  1. <body>
  2. <script>
  3. /**
  4. $.ajax({
  5. url: '请求地址',
  6. type: 'GET/POST',// 请求类型
  7. data: {}, // 请求参数,发送到服务器的数据
  8. dataType: 'json', // 返回的数据格式
  9. success: function (res) {}, // 成功的回调
  10. error: function(err) {} // 出错的回调
  11. })
  12. */
  13. $.ajax({
  14. url:'http://localhost:3000/users',
  15. type:'get',
  16. data:{id:2},//如果data省略,返回的就是所有的数据
  17. dataType:'text',//默认返回的是js对象(因为jquery自动帮你把返回的json字符串转成js对象了),如果就想获取json字符串,就写text
  18. success:function(res){
  19. console.log(res);
  20. console.log(typeof res);
  21. }
  22. })
  23. </script>
  24. </body>

示例 post请求

  1. <body>
  2. <button>新增</button>
  3. <script>
  4. $('button').click(function(){
  5. $.ajax({
  6. url:'http://localhost:3000/users',
  7. type:'post',//请求方式
  8. data:{name:'前妻',age:27},
  9. dataType:'json',//响应过来数据的格式
  10. success:function(res){
  11. console.log(res);
  12. console.log(typeof res);
  13. }
  14. })
  15. })
  16. </script>
  17. </body>

2 $.get()方法

$.get()是发送get请求的简写方式

语法

格式:
$get(url, [data], [callback], [type])
url:待载入页面的URL地址
data:待发送 Key/value 参数。
callback:载入成功时回调函数。
type:返回内容格式,xml, html, script, json, text, _default。

  1. $.get("url", {params}, callback)

示例

  1. $.get('http://localhost:3000/users', {id: 1}, function(res) {
  2. console.log(res)
  3. })

3 $.post()方法

$.post()是发送post请求的简写方式

语法

  1. $.post("url", {params}, callback)

示例

  1. $.post('http://localhost:3000/users', {name: 'xxp', age: 1}, function(res) {
  2. console.log(res)
  3. })

四. 跨域请求

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’)

  1. 前端
  2. ```html
  3. <!DOCTYPE html>
  4. <html lang="en">
  5. <head>
  6. <meta charset="UTF-8" />
  7. <title>Document</title>
  8. <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js"></script>
  9. </head>
  10. <body>
  11. <script type="text/javascript">
  12. $.ajax({
  13. url: 'http://localhost:3000/users',
  14. data: { id: 1 },
  15. dataType: 'json',
  16. success: function (res) {
  17. console.log(res)
  18. },
  19. })
  20. </script>
  21. </body>
  22. </html>

演示

AJAX - 图1

4 如何解决跨域问题

a 在服务端设置响应头

目前, 最主流的方式是CORS, 通过在服务端设置响应头, 允许跨域请求

跨源资源共享 Cross-Origin Resource Sharing(CORS) 是一个新的 W3C 标准,它新增的一组HTTP首部字段,允许服务端其声明哪些源站有权限访问哪些资源。换言之,它允许浏览器向声明了 CORS 的跨域服务器,发出 XMLHttpReuest 请求,从而克服 Ajax 只能同源使用的限制

配置上非常简单, 只需要在后端设置响应头即可

  1. // 设置响应头
  2. res.writeHead('200', {
  3. 'Access-Control-Allow-Origin': '*',
  4. })

b 在服务端开启CORS

在服务端开启CORS, 在服务端回复的响应头中, 加入特殊的头信息, 允许浏览器发送跨域请求

在后端安装cors中间件

https://www.npmjs.com/package/cors

  1. npm i cors

在app.js中导入cors中间件

  1. const cors = require('cors')

全局注册cors()中间件

  1. app.use(cors())

解决方法: 其实也是在服务端的响应头中,设置

  1. res.append('Access-Control-Allow-Origin','*')