• 简单封装ajax请求函数


    利用ES8中的async,await关键字自己简单分装一个Ajax请求函数

    1. 首页我们定义一个函数叫做sendAjax,函数内部我们需要返回一个promise对象,这样我们后续就不用通过.then 和.catch这种原始的方法去获取对应的值了
    function sendAjax(method, url) {
            return new Promise((resolve, reject) => {
              //  创建一个XMLHttpRequest实例
              const xhr = new XMLHttpRequest()
              // 传递参数
              xhr.open(method, url)
              // 发送请求
              xhr.send()
              // 监听事件
              xhr.onreadystatechange = function () {
                if (xhr.readyState == 4) {
                  if (xhr.status >= 200 && xhr.status < 300) {
                    // 请求成功
                    resolve(xhr.responseText)
                  } else {
                    // 请求资源失败
                    reject(xhr.status)
                  }
                }
              }
            })
     }
    
    
    1. 接下来我们需要去发送网络请求,去请求数据了

       	// 测试
      	// 我们先使用原来的.then()的方式去获取返回值吧
      
            // 注意这里sendAjax中返回的是一个promise对象
            const result = sendAjax('get', 'https://api.apiopen.top/getJoke').then(
              (result) => console.log(result),
              (reason) => console.log(reason)
            )
            
            
            
          // 在利用配合 async 和 await 尝试一下
            async function main() {
              const result = await sendAjax('get', 'https://api.apiopen.top/getJoke')
              console.log(result)
            }
            main()
      
      
         	//注意这里await 函数必须要放到async 函数中 
      

    哈哈哈啊 请求数据成功!

  • 相关阅读:
    SQL性能--left join和inner join的运行速度与效率
    20分钟搭建selenium+python+pydev+eclipse环境
    python 模拟双色球输出
    python 装饰器
    leetcode python丑数
    leetcode python找不同
    TCP和UDP的区别以及使用python服务端客户端简单编程
    python 上台阶
    leetcode python快乐数
    mysql 两例习题
  • 原文地址:https://www.cnblogs.com/comyan/p/13456826.html
Copyright © 2020-2023  润新知