这回图片少,给手动替换了~祝看得愉快,学的顺畅!哈哈
一 原生ajax经典四步
(一) 原生ajax经典四步
- 第一步:创建网络请求的AJAX对象(使用XMLHttpRequest)
|-------------------------------------------|
| JavaScript let xhr = new XMLHttpRequest() |
- 第二步:监听对象状态的变化
- 监听XMLHttpRequest对象状态的变化
|-------------------------------------------------------------------------------------------------------------|
| JavaScript xhr.onreadystatechange = function () { if (xhr.readyState == 4) { console.log(xhr.response); } } |
- 或者监听onload事件(请求完成时触发)
|---------------------------------------------------------------------------|
| JavaScript // 等价于下面这么写 xhr.onload = () => { console.log(xhr.response); } |
- 第三步:配置网络请求(通过open方法)
|-------------------------------------------------------------|
| JavaScript xhr.open("get", "http://127.0.0.1:3001/getData") |
- 第四步:发送send网络请求
send()参数写的是请求体 只有post请求方式才有请求体
就是给后端传递数据
|-----------------------|
| JavaScript xhr.send() |
(二) 原生ajax请求前后端代码示例
1.package.json用到的依赖
|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| JSON { "name": "code", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "dependencies": { "@koa/router": "^12.0.0", "axios": "^0.27.2", "body-parser": "^1.19.0", "cookie-parser": "^1.4.5", "express": "^4.17.1", "express-session": "^1.17.2", "koa": "^2.13.4", "koa-body": "^5.0.0", "koa-bodyparser": "^4.4.0", "koa-logger": "^3.2.1", "koa-static": "^5.0.0", "koa2-cors": "^2.0.6", "moment": "^2.30.1", "mongodb": "^4.4.0", "nprogress": "^0.2.0", "qs": "^6.10.2" }, "author": "", "license": "ISC" } |
2.前端代码:发送ajax请求
|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| HTML <script> // 第一步:创建网络请求的AJAX对象(使用XMLHttpRequest) let xhr = new XMLHttpRequest() // 第二步:监听XMLHttpRequest对象状态的变化,或者监听onload事件(请求完成时触发) // 方式一 onreadystatechange xhr.onreadystatechange = function () { if (xhr.readyState == 4) { console.log(xhr.response); } } // 方式二 onload // xhr.onload = () => { // console.log(xhr.response); // } // 第三步:配置网络请求(通过open方法) xhr.open("get", "http://127.0.0.1:3001/getData") // 第四步:发送send网络请求 xhr.send() </script> |
3.后端代码:监听到后接收请求并响应
|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| JavaScript const Koa = require("koa"); const cors = require("koa2-cors"); const logger = require("koa-logger"); const Router = require("@koa/router"); //路由 const koaBody = require("koa-body"); const app = new Koa(); const router = new Router(); //路由 app.use(cors()); app.use(logger()); app.use(koaBody()); // 写了一个接口 请求方式是get 请求的api是/getData // 请求返回的状态码是200 返回的结果是helloajax router.get("/getData", async (ctx, next) => { ctx.status = 200 ctx.body = "helloajax" }) app.use(router.routes()) //允许任意方式发送的请求 router.allowedMethods() //监听端口 app.listen(3001,()=>{ console.log("服务器跑起来了"); }) |
二 处理后端响应的数据
(一) 后端相应json数据
- 前端设置:xhr.responseType = 'json' 将得到的json串转成对象
- 后端设置:ctx.type = "json"
1.前端代码:发送ajax请求
|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| HTML <script> // 1)创建对象 let xhr = new XMLHttpRequest() // 2)绑定load事件 xhr.onload = function () { // 在network面板中 找到响应头,看到响应的数据类型是: // Content-Type:application/json; charset=utf-8 console.log(xhr.response);//从{"name":"哈哈"}变成{name:"哈哈"} } // 可以通过xhr.responseType这种方式,将得到的json串转成对象 xhr.responseType = 'json' // 3)配置网络请求 xhr.open('get', 'http://127.0.0.1:3001/json') // 4)发送请求 xhr.send() </script> |
2.后端代码:监听到后接收请求并响应json格式数据
|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| JavaScript const Koa = require("koa"); const cors = require("koa2-cors"); const logger = require("koa-logger"); const Router = require("@koa/router"); const koaBody = require("koa-body"); const app = new Koa(); const router = new Router(); app.use(cors()); app.use(logger()); app.use(koaBody()); router.get("/json", async (ctx) => { ctx.status = 200 ctx.type = "json" ctx.body = { name: "哈哈" //无论是json格式还是对象格式都会被浏览器自动转为json格式传输,所以都可 //"name": "哈哈" } }) app.use(router.routes()) router.allowedMethods() app.listen(3001, () => { //启动服务器并监听特定端口的方法 console.log("服务器跑起来了"); }) |
(二) 后端响应xml的数据
- 前端设置:xhr.responseType = 'json' 将得到的json串转成对象
- 后端设置:ctx.type = "xml"
1.前端代码:发送ajax请求
|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| JavaScript <script> let xhr = new XMLHttpRequest() xhr.onload = () => { //用xhr.responseXML获取返回数据,不用xhr.response console.log(xhr.responseXML ); } xhr.open("get", "http://127.0.0.1:3001/xml") xhr.send() </script> |
2.后端代码:监听到后接收请求并响应xml格式数据
|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| JavaScript const Koa = require("koa"); const cors = require("koa2-cors"); const logger = require("koa-logger"); const Router = require("@koa/router"); const koaBody = require("koa-body"); const app = new Koa(); const router = new Router(); app.use(cors()); app.use(logger()); app.use(koaBody()); router.get("/xml", async (ctx) => { ctx.status = 200 ctx.type = "xml" ctx.body = ` <content> <name>哈哈</name> </content>` }) app.use(router.routes()) router.allowedMethods() app.listen(3001, () => { console.log("服务器跑起来了"); }) |
三 前端发送请求传递参数/数据
(一) get传参
1.方式一: query
前端传参:xhr.open('get', 'http://127.0.0.1:3002/getData**?** name = zhangsan & address=zz')
后端获取:ctx.query
2.方式二: params
看network面板:通过params传参 并没有payload选项
前端传参:xhr.open("get", "http://127.0.0.1:3002/getData**/** zhangsan**/**18")
后端获取:ctx.params
3.代码示例
- 前端代码
|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| HTML <script> let xhr = new XMLHttpRequest() xhr.onload = () => { console.log(xhr.response); } xhr.responseType = "json" // ---------------------------------------------------- // get传参的第一种方式: 通过query传参 xhr.open('get', 'http://127.0.0.1:3002/getData?name=zhangsan\&address=zz') // 重点: 看network面板 // 请求地址b:Request URL:http://127.0.0.1:3000/get?name=zhangsan\&age=18\&address=zz // 在network里面,有一个payload,表示传递给服务器的参数 // payload -- Query String Parameters 查询字符串 // view source: 查看参数的源码 // view parsed: 解析参数 name=zhangsan&age=18&address=zz // 注意:前端给后端传递的数据非常重要 如果你调用接口失败了,你要考虑是否是你的参数传递问题 // ---------------------------------------------------- // get传参的第二种方式: 通过params传参 // 看network面板:通过params传参 并没有payload选项 // xhr.open("get", "http://127.0.0.1:3002/getData/zhangsan/18") xhr.send() </script> |
- 后端代码
|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| JavaScript const Koa = require("koa"); const cors = require("koa2-cors"); const logger = require("koa-logger"); const Router = require("@koa/router"); const koaBody = require("koa-body"); const app = new Koa(); const router = new Router(); app.use(cors()); app.use(logger()); app.use(koaBody()); // get -- query传参 router.get("/getData", (ctx) => { ctx.status = 200 // 前端请求服务器传递的参数 后端又响应给我们 ctx.body = ctx.query console.log(ctx.query.name); }) // get -- params传参 动态路由 // router.get("/getData/:name/:age ", (ctx) => { // ctx.status = 200 // // 前端请求服务器传递的参数 后端又响应给我们 // ctx.body = ctx.params // }) app.use(router.routes()) router.allowedMethods(); app.listen(3002, () => { console.log("running in http://127.0.0.1:3002"); }) |
(二) post传参(通过send(请求体))
|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| 默认情况下,看network面板中,请求头request Header里面 有一个 Content-Type:text/plain;charset=UTF-8 -- 表示给服务器默认传递的是纯文本的参数类型 再看payload,里面显示的是 Request Payload name=zhangsan&age=18&address=zz 但是在开发中,需要传递json格式 ++++1)x-www-form-urlencode++++ ++++2)json++++ ++++3)formdata++++ |
1.传递"name=zhangsan&age=18"类型数据(setRequestHeader)
前端传参:
xhr.open("post", "http://127.0.0.1:3002/postData")
xhr.send("name=zhangsan&age=18&address=zz")
设置请求头:xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
后端获取:ctx.request.body
代码示例:
- 前端代码
|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| HTML <script> let xhr = new XMLHttpRequest() xhr.onload = () => { console.log(xhr.response); } xhr.responseType = "json" xhr.open("post", "http://127.0.0.1:3002/postData") // post传参 需要把参数放在请求体中 // send('请求体') xhr.send("name=zhangsan&age=18&address=zz") </script> |
- 后端代码
|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| JavaScript const Koa = require("koa"); const cors = require("koa2-cors"); const logger = require("koa-logger"); const Router = require("@koa/router"); const koaBody = require("koa-body"); const app = new Koa(); const router = new Router(); app.use(cors()); app.use(logger()); app.use(koaBody()); router.post("/postData", (ctx) => { ctx.status = 200 // 接受post传递过来的数据 ctx.body = ctx.request.body console.log(ctx.request.body.name); }) app.use(router.routes()) router.allowedMethods() app.listen(3002, () => { console.log("running in http://127.0.0.1:3002"); }) |
2.传递json数据(setRequestHeader)
前端传参:
xhr.open("post", "http://127.0.0.1:3002/postData")
xhr.send(JSON.stringify({ name: "zhangsan", age: 18 }))
设置请求头:xhr.setRequestHeader('Content-Type', 'application/json')
后端获取:ctx.request.body
代码示例:
- 前端代码
|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| HTML <script> let xhr = new XMLHttpRequest() xhr.onload = () => { console.log(xhr.response); } xhr.responseType="json" xhr.open("post", "http://127.0.0.1:3001/postData") // 设置请求头 // application / json 表示以json形式传递 xhr.setRequestHeader('Content-Type', 'application/json') // xhr.send(JSON.stringify({ name: "zhangsan", age: 18 })) xhr.send(JSON.stringify({ name: "zhangsan", age: 18 })) </script> |
- 后端代码:同上
2.传递formData数据(FormData)
前端传参:
xhr.open("post", "http://127.0.0.1:3002/postData")
let formData = new FormData(formEle) 容器 -- formEle元素的数据
xhr.send(formData)
PS:payload的view source跟其他不同
后端获取:ctx.request.body
代码示例:
- 前端代码
|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <form action="" class="info"> <input type="text" name="username"> <input type="text" name="pwd"> </form> <button class="send">发送请求</button> </head> <body> <script> let formEle = document.querySelector(".info") let btnEle = document.querySelector(".send") btnEle.onclick = function () { let xhr = new XMLHttpRequest() xhr.responseType = "json" xhr.onload = () => { console.log(xhr.response); } xhr.open("post", "http://127.0.0.1:3001/postData") // 容器 -- formEle元素的数据 let formData = new FormData(formEle) xhr.send(formData) } </script> </body> </html> |
- 后端代码:同上
四 案例:检测用户是否存在
|---------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------|
| | |
(一) 前端代码
|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>用户注册</h1> <form> <ul> <li>用户名:<input type="text" name="username" id="user"> <span id="msg"></span> </li> <li>密码:<input type="text" name="pws"></li> <li>确认密码:<input type="text" name="pws"></li> <li><input type="submit" value="注册"></li> </ul> </form> <script> // 获取元素 let unameEle = document.getElementById("user") let msg = document.getElementById("msg") // 绑定失焦事件 unameEle.onblur = function () { // 获得用户名值 //let uname = unameEle.value.trim() let uname = this.value.trim(); //console.log(uname); // 发送请求 // 声明ajax对象 let xhr = new XMLHttpRequest() // 监听onload状态 xhr.onload = () => { // 如果返回true--用户名可用 msg.textContent = xhr.response.msg msg.style.color = xhr.response.msgColor } // 后台Boolean类型传到前端变字符串类型,需设置xhr.responseType = "json" // 从json串转为对象 xhr.responseType = "json" // post版本 // 配置请求,传递参数 xhr.open("post", `http://127.0.0.1:3001/check\`) // 设置请求头,请求参数为x-www-form的格式 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded') // 发送请求 xhr.send(`uname={uname}\`) // get版本 // 配置请求,传递参数 // xhr.open("get", \`http://127.0.0.1:3001/check?uname={uname}`) // 发送请求 // xhr.send() } </script> </body> </html> |
(二) 后端代码
|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| JavaScript const Koa = require("koa"); const cors = require("koa2-cors"); const logger = require("koa-logger"); const Router = require("@koa/router"); const koaBody = require("koa-body"); const app = new Koa(); const router = new Router(); app.use(cors()); app.use(logger()); app.use(koaBody()); // 模拟从数据库中取到的用户信息 let userData = ["wc", "xq", "admin"]; // post版本 router.post("/check", (ctx) => { ctx.status = 200 ctx.type = 'json' // 如果在users中找到相同的则返回该用户名已经被注册 console.log(ctx.request.body.uname); if (userData.includes(ctx.request.body.uname)) { ctx.body = { code: 0, msg: "用户名已被占用", msgColor: "red" } // 反之 } else { ctx.body = { code: 1, msg: "用户名可用", msgColor: "green" } } }) // get版本 // 需求:如果在users中找到相同的则返回该用户名已经被注册,反之 // router.get("/check", (ctx) => { // ctx.type = 'json' // // console.log(ctx.query.name.trim()); // // 如果在users中找到相同的则返回该用户名已经被注册 // if (userData.includes(ctx.query.name.trim())) { // ctx.body = { // code: 0, // msg: "用户名已被占用", // msgColor: "red" // } // // 反之 // } else { // ctx.body = { // code: 1, // msg: "用户名可用", // msgColor: "green" // } // } // }) app.use(router.routes()) router.allowedMethods() app.listen(3001, () => { console.log("服务器启动"); }) |