Ajax学习
简介:
Ajax 代表异步 JavaScript 和 XML(Asynchronous JavaScript and XML)的缩写。它指的是一种在网页开发中使用的技术,通过在后台与服务器进行数据交换,实现页面内容的更新,而无需刷新整个页面。Ajax 技术可以使网页更加动态和交互性,提供更好的用户体验。
场景:
XML:
XML (eXtensible Markup Language) 是一种用于描述数据的标记语言。它被设计用于传输和存储数据,同时具有跨平台和跨应用程序的特性。XML 使用标记来标识和组织数据,类似于 HTML,但不同于 HTML,XML 的目标是描述数据,传输数据而不是展示数据。
| <student> |
| <name>孙悟空</name> |
| <age>18</age> |
| <gender>男</gender> |
| </student> |
复制
| <person> |
| <name>John Doe</name> |
| <age>30</age> |
| <email>john.doe@example.com</email> |
| </person> |
复制
JSON:
JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于 JavaScript 的语法,但已成为一种独立于编程语言的通用数据格式。JSON 使用易于阅读和编写的文本格式,用于表示结构化的数据。
| {"name":"孙悟空","age":18,"gender":"男"} |
复制
| { |
| "name": "John Doe", |
| "age": 30, |
| "email": "john.doe@example.com", |
| "hobbies": ["reading", "traveling", "photography"], |
| "address": { |
| "street": "123 Main St", |
| "city": "Exampleville", |
| "country": "USA" |
| } |
| } |
复制
服务端框架:
因为Ajax的学习需要与服务器端进行交互,为了学习方便,我们采用express框架作为服务器端。
官网:Express/Node 入门 - 学习 Web 开发 | MDN (mozilla.org)
环境安装:
| npm init --yes |
| npm i express |
复制
express的基本使用
| |
| const express = require('express'); |
| |
| const app = express(); |
| |
| |
| |
| |
| app.get('/', (request, response)=>{ |
| |
| response.send('HELLO EXPRESS'); |
| }); |
| |
| |
| app.listen(8000, ()=>{ |
| console.log("服务已经启动, 8000 端口监听中...."); |
| }); |
复制


原生框架:
get请求:
| <!DOCTYPE html> |
| <html lang="en"> |
| <head> |
| <meta charset="UTF-8"> |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> |
| <title>AJAX GET 请求</title> |
| <style> |
| #result{ |
| width:200px; |
| height:100px; |
| border:solid 1px #90b; |
| } |
| </style> |
| </head> |
| <body> |
| <button>点击发送请求</button> |
| <div id="result"></div> |
| |
| <script> |
| |
| const btn = document.getElementsByTagName('button')[0]; |
| const result = document.getElementById("result"); |
| |
| btn.onclick = function(){ |
| |
| const xhr = new XMLHttpRequest(); |
| |
| xhr.open('GET', 'http://127.0.0.1:8000/server?a=100&b=200&c=300'); |
| |
| xhr.send(); |
| |
| xhr.onreadystatechange = function(){ |
| |
| if(xhr.readyState === 4){ |
| |
| 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; |
| }else{ |
| |
| } |
| } |
| } |
| |
| |
| } |
| </script> |
| </body> |
| </html> |
复制
后台服务器,服务器是用express框架搭建起来的本地服务器。
| |
| const express = require('express'); |
| |
| |
| const app = express(); |
| app.get('/', (request, response) => { |
| |
| response.send('HELLO EXPRESS'); |
| }); |
| |
| |
| app.get('/server', (request, response) => { |
| |
| response.setHeader('Access-Control-Allow-Origin', '*'); |
| |
| response.send('HELLO AJAX - 2'); |
| }); |
| |
复制
我们看一下点击后的结果:

post请求:
| <!DOCTYPE html> |
| <html lang="en"> |
| |
| <head> |
| <meta charset="UTF-8"> |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> |
| <title>AJAX POST 请求</title> |
| <style> |
| #result { |
| width: 200px; |
| height: 100px; |
| border: solid 1px #bfa; |
| } |
| </style> |
| </head> |
| |
| <body> |
| <div id="result"></div> |
| <script> |
| |
| const result = document.getElementById("result"); |
| |
| |
| result.addEventListener("mouseover", function () { |
| |
| const xhr = new XMLHttpRequest(); |
| |
| xhr.open('POST', 'http://127.0.0.1:8000/server'); |
| |
| xhr.send('a=100&b=200&c=300'); |
| |
| xhr.onreadystatechange = function () { |
| |
| if (xhr.readyState === 4) { |
| if (xhr.status >= 200 && xhr.status < 300) { |
| |
| result.innerHTML = xhr.response; |
| } |
| } |
| } |
| }); |
| </script> |
| </body> |
| |
| </html> |
复制
| |
| const express = require('express'); |
| |
| |
| const app = express(); |
| app.get('/', (request, response) => { |
| |
| response.send('HELLO EXPRESS'); |
| }); |
| |
| app.post('/server', (request, response) => { |
| |
| response.setHeader('Access-Control-Allow-Origin', '*'); |
| |
| response.send('HELLO AJAX - 2 post'); |
| }); |
复制

请求头:
下面我们看下如何设置请求头参数:
| <!DOCTYPE html> |
| <html lang="en"> |
| |
| <head> |
| <meta charset="UTF-8"> |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> |
| <title>AJAX POST 请求</title> |
| <style> |
| #result { |
| width: 200px; |
| height: 100px; |
| border: solid 1px #bfa; |
| } |
| </style> |
| </head> |
| |
| <body> |
| <div id="result"></div> |
| <script> |
| const result = document.getElementById("result"); |
| result.addEventListener("mouseover", function () { |
| |
| const xhr = new XMLHttpRequest(); |
| |
| xhr.open('POST', 'http://127.0.0.1:8000/server'); |
| |
| xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); |
| |
| |
| |
| xhr.send('a=100&b=200&c=300'); |
| |
| xhr.onreadystatechange = function () { |
| |
| if (xhr.readyState === 4) { |
| if (xhr.status >= 200 && xhr.status < 300) { |
| |
| result.innerHTML = xhr.response; |
| } |
| } |
| } |
| }); |
| </script> |
| </body> |
| |
| </html> |
复制

自定义请求头:
| <!DOCTYPE html> |
| <html lang="en"> |
| |
| <head> |
| <meta charset="UTF-8"> |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> |
| <title>AJAX POST 请求</title> |
| <style> |
| #result { |
| width: 200px; |
| height: 100px; |
| border: solid 1px #bfa; |
| } |
| </style> |
| </head> |
| |
| <body> |
| <div id="result"></div> |
| <script> |
| |
| const result = document.getElementById("result"); |
| result.addEventListener("mouseover", function () { |
| const xhr = new XMLHttpRequest(); |
| xhr.open('POST', 'http://127.0.0.1:8000/server'); |
| xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); |
| xhr.setRequestHeader('name', 'demo'); |
| |
| xhr.send('a=100&b=200&c=300'); |
| |
| |
| |
| xhr.onreadystatechange = function () { |
| |
| if (xhr.readyState === 4) { |
| if (xhr.status >= 200 && xhr.status < 300) { |
| |
| result.innerHTML = xhr.response; |
| } |
| } |
| } |
| }); |
| </script> |
| </body> |
| |
| </html> |
复制
| |
| app.all('/server', (request, response) => { |
| |
| response.setHeader('Access-Control-Allow-Origin', '*'); |
| |
| response.setHeader('Access-Control-Allow-Headers', '*'); |
| |
| response.send('HELLO AJAX POST'); |
| }); |
复制

JSON:
有一个问题,在ajax中后台只能给前台传递字符串,但是json对象是一个键值对形式的对象,我们不能传递对象,所以在服务器端需要使用 JSON.stringify() 将json对象专户为json字符串,这样就可以发送了。同样的我们前端对后端传递过来的json字符串,需要重新转化为json对象,调用JSON.parse() 这个方法。
| <!DOCTYPE html> |
| <html lang="en"> |
| <head> |
| <meta charset="UTF-8"> |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> |
| <title>JSON响应</title> |
| <style> |
| #result{ |
| width:200px; |
| height:100px; |
| border:solid 1px #89b; |
| } |
| </style> |
| </head> |
| <body> |
| <div id="result"></div> |
| <script> |
| const result = document.getElementById('result'); |
| |
| window.onkeydown = function(){ |
| const xhr = new XMLHttpRequest(); |
| xhr.responseType = 'json'; |
| xhr.open('GET','http://127.0.0.1:8000/json-server'); |
| xhr.send(); |
| xhr.onreadystatechange = function(){ |
| if(xhr.readyState === 4){ |
| if(xhr.status >= 200 && xhr.status < 300){ |
| |
| |
| |
| |
| result.innerHTML = xhr.response.name; |
| } |
| } |
| } |
| } |
| </script> |
| </body> |
| </html> |
复制
| app.all('/json-server', (request, response) => { |
| |
| response.setHeader('Access-Control-Allow-Origin', '*'); |
| |
| response.setHeader('Access-Control-Allow-Headers', '*'); |
| const data = { |
| name: 'demo' |
| }; |
| |
| let str = JSON.stringify(data); |
| |
| response.send(str); |
| }); |
复制

复制
请求超时控制:
js中定时器的实现:
| setTimeout(() => { |
| response.send('延时响应'); |
| }, 1000) |
复制
| <!DOCTYPE html> |
| <html lang="en"> |
| <head> |
| <meta charset="UTF-8"> |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> |
| <title>请求超时与网络异常</title> |
| <style> |
| #result{ |
| width:200px; |
| height:100px; |
| border:solid 1px #90b; |
| } |
| </style> |
| </head> |
| <body> |
| <button>点击发送请求</button> |
| <div id="result"></div> |
| <script> |
| |
| const btn = document.getElementsByTagName('button')[0]; |
| |
| const result = document.querySelector('#result'); |
| btn.addEventListener('click', function(){ |
| const xhr = new XMLHttpRequest(); |
| |
| xhr.timeout = 2000; |
| |
| xhr.ontimeout = function(){ |
| alert("网络异常, 请稍后重试!!"); |
| } |
| |
| xhr.onerror = function(){ |
| alert("你的网络似乎出了一些问题!"); |
| } |
| xhr.open("GET",'http://127.0.0.1:8000/delay'); |
| xhr.send(); |
| xhr.onreadystatechange = function(){ |
| if(xhr.readyState === 4){ |
| if(xhr.status >= 200 && xhr.status< 300){ |
| result.innerHTML = xhr.response; |
| } |
| } |
| } |
| }) |
| </script> |
| </body> |
| </html> |
复制
| |
| app.all('/delay', (request, response) => { |
| response.setHeader('Access-Control-Allow-Origin', '*'); |
| response.setHeader('Access-Control-Allow-Headers', '*'); |
| setTimeout(() => { |
| response.send('延时响应'); |
| }, 1000) |
| }); |
复制


请求取消:
| <!DOCTYPE html> |
| <html lang="en"> |
| <head> |
| <meta charset="UTF-8"> |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> |
| <title>取消请求</title> |
| </head> |
| <body> |
| <button>点击发送</button> |
| <button>点击取消</button> |
| <script> |
| |
| const btns = document.querySelectorAll('button'); |
| let x = null; |
| |
| btns[0].onclick = function(){ |
| x = new XMLHttpRequest(); |
| x.open("GET",'http://127.0.0.1:8000/delay'); |
| x.send(); |
| } |
| |
| btns[1].onclick = function(){ |
| x.abort(); |
| } |
| </script> |
| </body> |
| </html> |
复制

重复请求:
如果用户多次向服务端请求,到导致服务器压力很大,我们可以对多次请求只保留一次。如果点击多次,取出前面的请求,保留最后一次请求。
| <!DOCTYPE html> |
| <html lang="en"> |
| <head> |
| <meta charset="UTF-8"> |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> |
| <title>重复请求问题</title> |
| </head> |
| <body> |
| <button>点击发送</button> |
| <script> |
| |
| const btns = document.querySelectorAll('button'); |
| let x = null; |
| |
| let isSending = false; |
| |
| btns[0].onclick = function(){ |
| |
| if(isSending) x.abort(); |
| x = new XMLHttpRequest(); |
| |
| isSending = true; |
| x.open("GET",'http://127.0.0.1:8000/delay'); |
| x.send(); |
| |
| x.onreadystatechange = function(){ |
| if(x.readyState === 4){ |
| |
| isSending = false; |
| } |
| } |
| } |
| |
| |
| btns[1].onclick = function(){ |
| x.abort(); |
| } |
| </script> |
| </body> |
| </html> |
复制
| app.all('/delay', (request, response) => { |
| response.setHeader('Access-Control-Allow-Origin', '*'); |
| response.setHeader('Access-Control-Allow-Headers', '*'); |
| setTimeout(() => { |
| response.send('延时响应'); |
| }, 3000) |
| }); |
| |
复制

JQuery
我向搭建一个网页,用于测试三种发送方式。

| |
| app.all('/jquery-server', (request, response) => { |
| |
| response.setHeader('Access-Control-Allow-Origin', '*'); |
| response.setHeader('Access-Control-Allow-Headers', '*'); |
| |
| const data = { name: '我是帅哥' }; |
| response.send(JSON.stringify(data)); |
| }); |
复制
get:
四个参数 : 请求的url ,发送参数对象,回调函数 ,响应体类型
| $('button').eq(0).click(function(){ |
| $.get('http://127.0.0.1:8000/jquery-server', {a:100, b:200}, function(data){ |
| console.log(data); |
| },'json'); |
| }); |
复制
复制

post:
| $('button').eq(1).click(function () { |
| $.post('http://127.0.0.1:8000/jquery-server', { a: 100, b: 200 }, function (data) { |
| console.log(data); |
| console.log(typeof data) |
| }); |
| }); |
| |
复制


不加上面的第四个参数,返回的就是字符串。
通用写法:
| $('button').eq(2).click(function () { |
| $.ajax({ |
| |
| url: 'http://127.0.0.1:8000/jquery-server', |
| |
| data: { a: 100, b: 200 }, |
| |
| type: 'GET', |
| |
| dataType: 'json', |
| |
| success: function (data) { |
| console.log(data); |
| console.log(typeof data); |
| }, |
| |
| timeout: 2000, |
| |
| error: function () { |
| console.log('出错啦!!'); |
| }, |
| |
| headers: { |
| c: 300, |
| d: 400 |
| } |
| }); |
| }); |
复制


| <!DOCTYPE html> |
| <html lang="en"> |
| |
| <head> |
| <meta charset="UTF-8"> |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> |
| <title>jQuery 发送 AJAX 请求</title> |
| <link crossorigin="anonymous" href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" |
| rel="stylesheet"> |
| <script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script> |
| </head> |
| |
| <body> |
| <div class="container"> |
| <h2 class="page-header">jQuery发送AJAX请求 </h2> |
| <button class="btn btn-primary">GET</button> |
| <button class="btn btn-danger">POST</button> |
| <button class="btn btn-info">通用型方法ajax</button> |
| </div> |
| <script> |
| $('button').eq(0).click(function () { |
| $.get('http://127.0.0.1:8000/jquery-server', { a: 100, b: 200 }, function (data) { |
| console.log(data); |
| }, 'json'); |
| }); |
| |
| $('button').eq(1).click(function () { |
| $.post('http://127.0.0.1:8000/jquery-server', { a: 100, b: 200 }, function (data) { |
| console.log(data); |
| console.log(typeof data) |
| }); |
| }); |
| |
| $('button').eq(2).click(function () { |
| $.ajax({ |
| |
| url: 'http://127.0.0.1:8000/jquery-server', |
| |
| data: { a: 100, b: 200 }, |
| |
| type: 'GET', |
| |
| dataType: 'json', |
| |
| success: function (data) { |
| console.log(data); |
| console.log(typeof data); |
| }, |
| |
| timeout: 2000, |
| |
| error: function () { |
| console.log('出错啦!!'); |
| }, |
| |
| headers: { |
| c: 300, |
| d: 400 |
| } |
| }); |
| }); |
| |
| </script> |
| </body> |
| |
| </html> |
复制
axios
Axios 是一个基于 Promise 的 JavaScript HTTP 客户端,用于浏览器和 Node.js 环境中发送 HTTP 请求。它提供了一种简洁、直观的方式来执行异步请求,并处理请求和响应的数据。
GitHub地址:https://github.com/axios/axios

get
| <!DOCTYPE html> |
| <html lang="en"> |
| |
| <head> |
| <meta charset="UTF-8"> |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> |
| <title>axios 发送 AJAX请求</title> |
| <script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/axios/0.19.2/axios.js"></script> |
| </head> |
| <body> |
| <button>GET</button> |
| <button>POST</button> |
| <button>AJAX</button> |
| <script> |
| const btns = document.querySelectorAll('button'); |
| |
| axios.defaults.baseURL = 'http://127.0.0.1:8000'; |
| btns[0].onclick = function () { |
| |
| axios.get('/axios-server', { |
| |
| params: { |
| id: 100, |
| vip: 7 |
| }, |
| |
| headers: { |
| name: 'demo', |
| age: 20 |
| } |
| }).then(value => { |
| console.log(value); |
| }); |
| } |
| |
| |
| |
| </script> |
| </body> |
| |
| </html> |
复制
后端服务器:
| |
| app.all('/axios-server', (request, response) => { |
| |
| response.setHeader('Access-Control-Allow-Origin', '*'); |
| |
| response.setHeader('Access-Control-Allow-Headers', '*'); |
| |
| const data = { name: '我是帅哥' }; |
| response.send(JSON.stringify(data)); |
| }); |
复制

请求得到的响应数据:

post:
| btns[1].onclick = function () { |
| axios.post('/axios-server', { |
| username: 'admin', |
| password: 'admin' |
| |
| }, { |
| |
| params: { |
| id: 200, |
| vip: 9 |
| }, |
| |
| headers: { |
| height: 180, |
| weight: 180, |
| } |
| }); |
| } |
| |
复制

通用方法:
| btns[2].onclick = function(){ |
| axios({ |
| |
| method : 'POST', |
| |
| url: '/axios-server', |
| |
| params: { |
| vip:10, |
| level:30 |
| }, |
| |
| headers: { |
| a:100, |
| b:200 |
| }, |
| |
| data: { |
| username: 'admin', |
| password: 'admin' |
| } |
| }).then(response=>{ |
| |
| console.log(response.status); |
| |
| console.log(response.statusText); |
| |
| console.log(response.headers); |
| |
| console.log(response.data); |
| }) |
| } |
复制


fetch
简介:
fetch
是一个用于发送 HTTP 请求的现代 JavaScript API,内置于浏览器中,可以在前端代码中使用。它提供了一种基于 Promise 的方式来发送和处理网络请求。
post:
| <!DOCTYPE html> |
| <html lang="en"> |
| <head> |
| <meta charset="UTF-8"> |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> |
| <title>fetch 发送 AJAX请求</title> |
| </head> |
| <body> |
| <button>AJAX请求</button> |
| <script> |
| |
| |
| |
| const btn = document.querySelector('button'); |
| |
| btn.onclick = function(){ |
| fetch('http://127.0.0.1:8000/fetch-server?vip=10', { |
| |
| method: 'POST', |
| |
| headers: { |
| name:'atguigu' |
| }, |
| |
| body: 'username=admin&password=admin' |
| }).then(response => { |
| |
| return response.json(); |
| }).then(response=>{ |
| console.log(response); |
| }); |
| } |
| </script> |
| </body> |
| </html> |
复制
| |
| app.all('/fetch-server', (request, response) => { |
| |
| response.setHeader('Access-Control-Allow-Origin', '*'); |
| response.setHeader('Access-Control-Allow-Headers', '*'); |
| const data = { name: '我是帅哥' }; |
| response.send(JSON.stringify(data)); |
| }); |
复制
