ajax函数封装

2018-11-05  本文已影响0人  郑宋君

ajax函数封装

ajax({
  url:'http://api.mock.json',
  data:{
    ciry:'北京'
  },
  onsuccess:function(e){
    console.log(e)  
  },
  onerror:function(){
    console.log('服务器异常')
  }
})

封装一个ajax

function ajax(obj){
  var url = obj.url
  var type = obj.type || 'GET'
  var dataType = obj.dataType || 'json'
  var onsuccess = obj.onsuccess || function(){}
  var onerror = obj.onerror || function(){}
  
  var dataStr = []
  for(var key in data){
    data.Str.push(key+'='+data[key])
  }
  dataStr = dataStr.join('&')
  if(type == 'GET'){
    url +='?'+dataStr
  }
  var xhr = new XMLHttpRequest()
  xhr.open(type,url,true)
  xhr.onload = function(){
    if( (xhr.status >=200 && xhr.status < 300) || xhr.status ==304){
        //成功了
    if(dataType === 'json'){
        onsuccess(JSON.parse(xhr.responseText))
    }else{
        onsuccess(xhr.responseText)
    }
  }
 } 

}
上一篇 下一篇

猜你喜欢

热点阅读