ajax简单封装

  <script>
   function hdcajax ({
    url,
    method = "get",
    data = {},
    timeout = 1000,
    headers = {},
    success,
    failure
   }={}){
    //1.创建对象
    const xhr = new XMLHttpRequest()
    //2.监听状态变化
    xhr.onload = function(){
      if(xhr.status >=200 && xhr.status<300){
        success && success(xhr.response)
      }else{
        failure && failure({status:xhr.status,message:xhr.statusText})
      }
    }
    //3.设置类型
    xhr.responseType="json"
    //open方法
    //5.发送请求
    if(method == "get"||method == "GET"){
      let queryStrings = []
      for(const key in data){
        queryStrings.push(`${key} = ${data[key]}`)
      }
      xhr.open(method,url+`?`+queryStrings.join("&"))
      xhr.send()
    }
    else{
      xhr.open(method,url)
      xhr.setRequestHeader("Content-Type","application/json")
      xhr.send(JSON.stringify(data))
    }
    
   }
   //调用者:
   hdcajax({
    url:"http://123.207.32.32:1888/02_param/get",
    success:function(res){console.log(res)},
    failure:function(err){alert(err.message)},
    data:{
      name:"jsondata",
      age:"22"
    },
   })
  // hdcajax({
  //   url:"http://123.207.32.32:1888/02_param/postjson",
  //   method:"post",
  //   data:{
  //     name:"jsondata",
  //     age:"22"
  //   },
  //   success:function(res){console.log(res)},
  //   failure:function(err){alert(err.message)}
  //  })
  </script>

使用promise

  function hdcajax ({
url,
method = "get",
data = {},
timeout = 1000,
headers = {},
}={}){
return new Promise ((resolve,reject)=>{
  //1.创建对象
    const xhr = new XMLHttpRequest()
    //2.监听状态变化
    xhr.onload = function(){
      if(xhr.status >=200 && xhr.status<300){
       resolve(xhr.response)
      }else{
        reject({status:xhr.status,message:xhr.statusText})
      }
    }
    //3.设置类型
    xhr.responseType="json"
    //open方法
    //5.发送请求
    if(method == "get"||method == "GET"){
      let queryStrings = []
      for(const key in data){
        queryStrings.push(`${key} = ${data[key]}`)
      }
      xhr.open(method,url+`?`+queryStrings.join("&"))
      xhr.send()
    }
    else{
      xhr.open(method,url)
      xhr.setRequestHeader("Content-Type","application/json")
      xhr.send(JSON.stringify(data))
    }
    
})
}
posted @ 2024-10-24 10:32  韩德才  阅读(2)  评论(0编辑  收藏  举报