封装ajax

ajax.js

/*
封装ajax的逻辑
  1 对参数的验证
    必填参数的验证
    选填参数的格式验证
  2 设置参数的默认值
  3 发送ajax请求信息
*/
function ajax(options={}){
  // 1 对参数进行验证
    // 1.1 url必填
    if(!options.url){
      throw Error('url必须填写')
      // 无需写return,报错会中断程序执行
    }
    // 1.2 method 可以不填,填写了必须是post或者get
    if(!(options.method === undefined || /^(get|post)$/i.test(options.method))){
      throw Error('请求方式错误,目前只支持post或者get请求')
    }
    // 1.3 async 可以不填,填写了必须是布尔值
    if(!(options.async === undefined || typeof options.async === 'boolean')){
      throw Error('async必须是布尔值')
    }
    // 1.4  data 可以不填,填写了必须是对象 携带给后端的数据
    if(!(options.data === undefined || Object.prototype.toString.call(options.data) === '[object Object]')){
      throw Error('携带的data数据必须是对象类型')
    }
    // 1.5  headers 可以不填,填写了必须是对象
    if(!(options.headers === undefined || Object.prototype.toString.call(options.headers) === '[object Object]')){
      throw Error('headers必须是对象类型')
    }
  //2 设置参数的默认值
    let info = {
      url: options.url,
      method: options.method || 'get',
      data: options.data || {},
      async: typeof options.async === 'boolean'?options.async : true,
      headers:{'content-type':'application/x-www-form-urlencoded',...options.headers},
      dataType: options.dataType || 'string',
      success:options.success || (()=>{}),
      error:options.error || (()=>{})
    }
    // 2.1 对info中的内部信息做调整
    // data是一个对象,在ajax请求的时候,需要把这个对象转为一个查询字符串
    let str = ''
    for(const key in options.data){
      str += `${key}=${info.data[key]}&`
    }
    info.data = str.slice(0,-1)
    // 根据method请求方式,拼接url
    if(/^get$/i.test(info.method) && info.data){
      info.url += `?${info.data}`
    }
    // console.log(info);
  // 3 发送ajax请求
    let xhr = new XMLHttpRequest()
    xhr.open(info.method,info.url,info.async)
    xhr.onload = function(){
      // 根据info.dataTyp的值决定要不要对后端返回的值进行解析
      let res = info.dataType === 'string' ? xhr.responseText : JSON.parse(xhr.responseText)
      info.success(res)
    }
  // 设置请求头信息
    for(let key in info.headers){
      xhr.setRequestHeader(key,info.headers[key])
    }
    if(/^get$/i.test(info.method)){
      xhr.send()
    }else{
      xhr.send(info.data)
    }
}

ajax调用.html

<script src="./封装ajax的参数验证.js"></script>
  <script>
    window.onload = function(){
      /*
      封装ajax
      设计哪些参数
        1 请求地址 url 必填 没有默认值
        2 请求方式 method 必填 默认值get
        3 携带给后端的数据 data 选填 {}
        4 是否异步 async 选填 tru表示异步
        5 是否解析后端返回的数据 dataType 选填 默认值string不执行JSON.parse() 选填json要执行JSON.parse()
        6 请求头信息 header 选填 默认值{'content-type','application/x-www-form-urlencoded'}
        7 执行成功后的函数 success 选填 默认值是一个空函数
        8 执行失败后的函数 error 选填 默认值是一个空函数
      设计函数的参数形式
        1 function ajax(url,method='get',async=true,data={}){}
        2 function ajax(options={})
      */
     ajax({
       url:'http://localhost:8888/test/third',
       method:'get',
       fataType:'json',
       async:true,
       data:{name:'kk',age:18},
       success(res){
         console.log('请求成功');
         console.log(res);
       },
       error(err){
         console.log(err);
       },
       headers:{authorization:'kkee'}
     })
    }
  </script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值