一篇文章看懂Ajax基本使用

这篇文章是看完B站up小满zs的视频Ajax全套_哔哩哔哩_bilibili,后整理的笔记。

在具体使用Ajax之前,我们需要配置后端接口,以便给前端提供接口

nodejs配置

首先我们使用node.js 提供后端接口

注意点一

nodejsexpress框架封装的请求注意:

  • get请求,携带的参数拼接到URL路径后面(<http://localhost:3000/api/get?name=jack&age=1>),通过req.query 获取。
  • post请求,携带的参数通过xhr.send(data)发送,通过req.body 获取

注意点二

注意请求跨域了,因为前端实际请求的端口和后端不一样,所以我们通过配置cors解决跨域问题。

cors代理仅设置Access-Control-Allow-Origin,对于简单请求(GET,POST,HEAD)没有自定义请求头可以,配置如下:

app.use('*', (req, res, next) => {
     res.header('Access-Control-Allow-Origin', '*')
    next()
})

但是对于非简单请求,浏览器发送一个预检请求options,需要检查cors头的三个部分: Access-Control-Allow-Methods:允许的方法(如GET、POST、PUT等)。 Access-Control-Allow-Headers:允许的请求头(如Content-Type、Authorization等)。 Access-Control-Allow-Credentials:是否允许发送凭据(如cookies) 例如:当带有自定义头Content-Type: application/json POST请求时候,因为缺少必要的cors头而被拒绝。

所以说我们的就需要给cors配置三个部分,配置如下

// 允许所以源,所有http请求方法,包含content-type的请求头
import cors from 'cors'
app.use(cors({
    origin:'*' ,//允许所有源
    methods:'GET,POST,PUT,DELETE,HEAD,PATCH',
    allowedHeaders:['Content-Type','Authorization']
}))

node.js完整代码如下

import express from 'express'
import fs from 'fs'
const app = express()
//中间件,解析json请求体
app.use(express.json())

// 允许所以源,所有http请求方法,包含content-type的请求头
import cors from 'cors'
app.use(cors({
    origin:'*' ,//允许所有源
    methods:'GET,POST,PUT,DELETE,HEAD,PATCH',
    allowedHeaders:['Content-Type','Authorization']
}))

// 1.post请求
app.post('/api/post',(req,res)=>{
    console.log(req.body)
    res.json({
        code:200
    })
})
// 2.get请求,读取文件
app.get('/api/txt', (req, res) => {
    // 方法一:同步读取文件readfilesync,但会造成用阻塞
    const data = fs.readFileSync('./mytext.txt', 'utf8')
    res.send(data)
    // 方法二:使用异步读取文件readfile,等到文件读取完成才会返回给客户端
    // fs.readFile('./mytext.txt', 'utf-8', (err, data) => {
    //     if (err) {
    //         return res.status(500).send('error reading file')
    //     }
    //     res.send(data)
    // })
})
app.listen(3001, () => {
    console.log('listen open')
})

html配置

在上面我们可以知道配置了cors,通过文件形式,直接在浏览器访问打开这个html页面。

但如果不使用cors,还有另一种方法,通过http-server开启本地服务器访问页面,需要做的就是修改这个port和后端的一样

具体操作:
1.npm i http-server -g
  //安装

2.http-server -p 3001   //开启本地服务器,访问本地的html页面,在浏览器http://127.0.0.1:3001 既可

一个完整的ajax的请求过程如下:

1.const xhr = new XMLHttpRequest()
//open方法,初始化请求,参数:(请求方法,地址,是否异步)
2.xhr.open('get','<http://localhost:3001/api/txt?name=11&age=11>',true)
4.//请求成功后的操作方法一
xhr.onreadystatechange = () => { // 监听readyState的变化
    if (xhr.readyState == 4 && xhr.status == 200) {
       console.log(xhr.responseText)
    }
}
4.//请求成功后的操作方法二,load事件就是readyState=4
xhr.addEventListener('load',()=>{
    if(xhr.status==200){
       console.log(xhr.responseText)
    }
})
3.发送open实际请求,send里面可以放要发送给服务器的数据
xhr.send(null)

注意

readyState0 未初始化,即XMLHttpRequest对象已经创建

readyState1 open方法已经调用,send未调用

readyState 2 发送请求 send方法已经调用 请求已被服务器接受

readyState3 处理请求 服务器正在处理请求并返回数据

readyState4 完成请求 服务器成功返回数据

设置请求超时时间,超时就取消请求

xhr.timeout=300
xhr.addEventListener('timeout',()=>{
    console.log('请求超时')
})

中断请求

xhr.abort()
xhr.addEventListener('abort',()=>{
   console.log('请求中断')
})

监听事件进度(比如文件上传或下载)作用:可以设置进度百分比

xhr.addEventListener('progress',(event)=>{
     console.log(event.loaded,event.total) //现在的进度,总进度
     //进度百分比:progress.innerHTML=`${(event.loaded/event.total*100).toFixed(2)}%`
})

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>
    <style>
    </style>
</head>

<body>
    <button id="btn">sendchage</button>
    <script>
        const btn = document.querySelector('#btn')
        btn.addEventListener('click', () => {
            sendajax()
        })
        const sendajax = () => {
            const xhr = new XMLHttpRequest()
            // 1.get请求读取文件内容
            xhr.open('get','<http://localhost:3001/api/txt?name=11&age=11>',true)
            xhr.onreadystatechange = () => {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    console.log(xhr.responseText)
                }
            }
            // get请求,没有请求数据
            xhr.send()

            // 2.post请求,携带json参数
            xhr.open('post', '<http://localhost:3001/api/post>', true)
            // 设置请求头,json格式,注意在open之后
            xhr.setRequestHeader('Content-Type', 'application/json')
            xhr.onreadystatechange = () => {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    console.log(xhr.responseText)
                }
            }
            //application/json post发送给服务器数据是json格式
            xhr.send(JSON.stringify({name:'jack'})) 

            // 3.post请求,携带字符串参数
            xhr.open('post', '<http://localhost:3001/api/post>', true)
            // 设置请求头,字符串类型,注意在open之后
            xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
            xhr.onreadystatechange = () => {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    console.log(xhr.responseText)
                }
            }
            //urlencoded post发送给服务器数据是字符串格式
            xhr.send('name=jack&age=11')
        }
    </script>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值