ajax的封装 | 青训营笔记

77 阅读3分钟

ajax的get请求(不带token)

    var xhr = new XMLHttpRequest();//创建xhr对象
    xhr.open('get','http://localhost:8888/test/first?name=zs&password=1234');// 配置请求相关信息
    xhr.send();//将请求发送出去
    xhr.onreadystatechange = function(){
        // 如果请求状态码为4(表示请求的内容已被服务器端接收完毕)  并求 响应的状态码是200(表示响应已成功)
         if(xhr.readyState==4&xhr.status==200){
            console.log(xhr.responseText);// 满足两个条件就拿到服务器端响应回来的数据
         }
    }

ajax的post请求(不带token)

    var xhr = new XMLHttpRequest();//创建xhr对象

    xhr.open('post','http://localhost:8888/test/first');// 配置请求相关信息
    xhr.setRequestHeader("content-type","application/x-www-form-urlencoded"); //设置请求头,告诉服务器我请求参数的格式类型
    xhr.send("name=zs&password=1234");//将请求发送出去并携带请求参数
       xhr.onreadystatechange = function(){
        // 如果请求状态码为4(表示请求的内容已被服务器端接收完毕)  并求 响应的状态码是200(表示响应已成功)
         if(xhr.readyState==4&xhr.status==200){
            console.log(xhr.responseText);// 满足两个条件就拿到服务器端响应回来的数据
         }
    }

问题

  • 哪个代码是异步的?
  • get和post请求携带请求参数时的不同点
  • 封装时哪些可以作为请求参数
    • 请求方式
    • url地址
    • 请求参数
    • 回调函数
  • 如何在函数外部取出函数内部的响应结果
    • 回调函数
  • onreadystatechange这个事件什么时候会触发 请求状态码发生改变 ()
  • 响应的结果xhr.responseText 的类型是什么类型? 字符串

ajax的get请求(带token)

  • token可以表示成身份令牌,在登陆成功的时候,服务器颁发的, 有些接口必须在登陆成功的时候才可以连接(购物车,获取用户信息)
    var xhr = new XMLHttpRequest();//创建xhr对象
    xhr.open('get','http://localhost:8888/users/info?name=zs&password=1234');// 配置请求相关信息
    xhr.setRequestHeader("authorization",'生成的token');// 告诉服务器 我带着token进来了
    xhr.send();//将请求发送出去
    xhr.onreadystatechange = function(){
        // 如果请求状态码为4(表示请求的内容已被服务器端接收完毕)  并求 响应的状态码是200(表示响应已成功)
         if(xhr.readyState==4&xhr.status==200){
            console.log(xhr.responseText);// 满足两个条件就拿到服务器端响应回来的数据
         }
    }

ajax的post请求(带token)

  • token可以表示成身份令牌,在登陆成功的时候,服务器颁发的, 有些接口必须在登陆成功的时候才可以连接(购物车,获取用户信息)
    var xhr = new XMLHttpRequest();//创建xhr对象
    xhr.open('get','http://localhost:8888/users/info?name=zs&password=1234');// 配置请求相关信息
    xhr.setRequestHeader("authorization",'生成的token');// 告诉服务器 我带着token进来了
    xhr.setRequestHeader("content-type","application/x-www-form-urlencoded"); //设置请求头,告诉服务器我请求参数的格式类型
    xhr.send("name=zs&password=1234");//将请求发送出去并携带请求参数
    xhr.onreadystatechange = function(){
        // 如果请求状态码为4(表示请求的内容已被服务器端接收完毕)  并求 响应的状态码是200(表示响应已成功)
         if(xhr.readyState==4&xhr.status==200){
            console.log(xhr.responseText);// 满足两个条件就拿到服务器端响应回来的数据
         }
    }
    
    这是最近学习到的ajax的封装,但是具体的内容还需要将他们组合到一起来,然后再进行共同的封装,