Ajax封装

1.原生Ajax请求数据过程

过程

  1. 初始化XMLHttpRequest对象

    var xhr = new XMLHttpRequest();
    
  2. 定义请求的地址和请求方式

    xhr.open(type, url);
    
    • type:

      • get

        • xhr.open('get', url);
          
      • post

        • // post方法需要设置参数格式
          xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
          // post方法的查询参数要写在send()里面  键值对的形式  例如:
          xhr.send('username=' + userVal + '&&userpwd=' + psdVal);
           // username=zhangsan&userpwd=123456
          //  form-urlencoded格式:  键与值之间是=  键值对之间是&   整体跟url拼接  前面要加?
          
  3. 确定发送请求

    xhr.send();
    
  4. 等待数据–确定接受到完整的数据

    xhr.onreadyStatechange = function() {
       // 当 readyState 等于 4 且状态为 200 时,表示响应已就绪:
                if (this.readyState === 4 && this.status === 200) {
                    console.log(this.responseText) //后台输出:这是我要的数据
                }
            }
    
    • onreadystatechange 事件

      注意: onreadystatechange 事件被触发 5 次(0 - 4),对应着 readyState 的每个变化。

    属性描述
    onreadystatechange存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。
    readyState存有 XMLHttpRequest 的状态。
    从 0 到 4 发生变化。
    0: 请求未初始化
    1: 服务器连接已建立
    2: 请求已接收
    3: 请求处理中
    4: 请求已完成,且响应已就绪
    status200, OK,访问正常
    201,已创建,请求成功且服务器已创建了新的资源
    301, Moved Permanently,永久移动
    302, Moved temporarily,暂时移动
    304, Not Modified,未修改
    307, Temporary Redirect,暂时重定向
    401, Unauthorized,未授权
    403, Forbidden,禁止访问
    404, Not Found,未发现指定网址
    500, Internal Server Error,服务器发生错误
    • readyState 属性–准备状态

      • 4代表接受完整数据
    • status 属性–状态码

      • 200代表成功
    • responseText 属性

      获得字符串形式的响应数据。

      • 返回数据:字符串

2.原生Ajax请求数据-完整版

function getData() {
            // 通过Ajax发送了一个http请求,并且获取了该地址返回的完整数据

            // 1. 初始化XHTTpRequest对象
            var xhr = new XMLHttpRequest();
            // 2. 定义请求方法,请求的地址
            xhr.open('get', '');
            // 3. 确定发送请求
            xhr.send();
            // 4. 等待数据--确定接受到完整的数据
            xhr.onreadystatechange = function() {
                // 当readyState 和 status 满足特定条件时,代表完整数据接受成功
                if (this.readyState === 4 && this.status === 200) {
                    console.log(this.responseText);
                    // 序列化:将json格式字符串转成数组
                    var res = JSON.parse(this.responseText);
                    console.log(res)
                }
            }
        }

3.封装Ajax

const myAjax = obj => {
            // 默认参数对象
            let params = {
                type: 'get',
                dataType: 'JSON',
                data: {}
            };
            // 将params和obj进行合并
            let newObj = Object.assign(params, obj);
            // console.log(newObj);

            let {
               type,
                url,
                // paramsQuery给data起的名字
                data: paramsQuery,
                success,
                dataType
            } = params
            // console.log(type, url, paramsQuery, success, dataType);
            // console.log(paramsQuery)

            
            //设置get方式传入的参数
            let str = '';
            // Object.keys(paramsQuery) 遍历对象的属性,返回值是数组形式的属性名['id']
            // 把数据转换成键值对形式放在url里面
            Object.keys(paramsQuery).forEach(item => str += `${item}=${paramsQuery[item]}&`)
            str = str.slice(0, -1);
            // console.log(str)

            // 获取ajax
            let xhr = new XMLHttpRequest();
    		//判断请求方式是哪种:
    		//--1.如果是get或者delete  参数需要写在url后面
            if (type.toUpperCase() === 'GET' || type.toUpperCase() === 'DELETE') {
                xhr.open(type, url + '?' + str);
                xhr.send();
            }
    		//--2.如果是post或者是put  需要设置请求头  参数写在send()中
            if (type.toUpperCase() === 'POST' || type.toUpperCase() === 'PUT') {
                xhr.open(type, url);
                xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
                xhr.send(str);
            }

            xhr.onreadystatechange = function() {
                if (this.readyState === 4 && this.status === 200) {
                    // 判断dataType  转换大小写
                    if (dataType.toUpperCase() === 'JSON') {
                        let result = JSON.parse(this.responseText);
                        success(result);
                        return
                    }
                    success(this.responseText);
                }
            }
        }
  • 测试:(使用下面提供的接口)
        // 获取图书
        myAjax({
            url: 'http://www.liulongbin.top:3006/api/getbooks',
            // 可选项
            // type: 'get',
            data: {},
            dataType: 'JSON',
            success: function(res) {
                console.log(res)
            }
        })

        // 删除图书
        myAjax({
            url: 'http://www.liulongbin.top:3006/api/delbook',
            data: {
                id: 278
            },
            dataType: 'json',
            success: function(res) {
                console.log(res)
            }
        });

        // 添加图书
        myAjax({
            url: 'http://www.liulongbin.top:3006/api/addbook',
            type: 'post',
            data: {
                id: 111,
                bookname: '活着',
                author: '余华',
                publisher: '北京十月文艺出版社出版'
            },
            dataType: 'json',
            success: function(res) {
                console.log(res)
            }
        });

4.提供的接口数据(可供参考)

图书管理接口文档

请求的根路径

http://www.liulongbin.top:3006

图书列表
  • 接口URL: /api/getbooks
  • 调用方式: GET
  • 参数格式:
参数名称参数类型是否必选参数说明
idNumber图书Id
booknameString图书名称
authorString作者
publisherString出版社
  • 响应格式:
数据名称数据类型说明
statusNumber200 成功;500 失败;
msgString对 status 字段的详细说明
dataArray图书列表
+idNumber图书Id
+booknameString图书名称
+authorString作者
+publisherString出版社
  • 返回示例:
{
  "status": 200,
  "msg": "获取图书列表成功",
  "data": [
    { "id": 1, "bookname": "西游记", "author": "吴承恩", "publisher": "北京图书出版社" },
    { "id": 2, "bookname": "红楼梦", "author": "曹雪芹", "publisher": "上海图书出版社" },
    { "id": 3, "bookname": "三国演义", "author": "罗贯中", "publisher": "北京图书出版社" }
  ]
}

删除图书
  • 接口URL: /api/delbook
  • 调用方式: GET
  • 参数格式:
参数名称参数类型是否必选参数说明
idNumber图书Id
  • 响应格式:
数据名称数据类型说明
statusNumber200 删除成功;500 未指定要删除的图书Id;501 执行Sql报错;502 要删除的图书不存在;
msgString对 status 字段的详细说明
  • 返回示例:
{
    "status": 200,
    "msg": "删除图书成功!"
}
添加图书
  • 接口URL: /api/addbook
  • 调用方式: POST
  • 参数格式:
参数名称参数类型是否必选参数说明
booknameString图书名称
authorString作者
publisherString出版社
  • 响应格式:
数据名称数据类型说明
statusNumber201 添加成功;500 添加失败;
msgString对 status 字段的详细说明
  • 返回示例:
{
    "status": 201,
    "msg": "添加图书成功"
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值