什么是Ajax?

2020-05-25  本文已影响0人  Zouch在路上

什么是ajax?

 let xhr = new XMLHttpRequest()
   xhr.open('POST', '/xxxx')
   xhr.onreadystatechange = function(){
     if(xhr.readyState === 4 && xhr.status === 200){
         console.log(xhr.responseText)
     }
 }
 xhr.send('a=1&b=2')

封装一个ajax:

function ajax(opts){

 let url = opts.url

 let type = opts.type || 'GET'

 let dataType = opts.dataType || 'json'

 let onsuccess = opts.onsuccess || function(){}

 let onerror = opts.onerror || function(){}

 let data = opts.data || {}

 let dataStr = []

 for(let key in data){

 dataStr.push(key + '=' + data[key])

 }

 dataStr = dataStr.join('&')
//判断请求类型
 if(type === 'GET'){

 url += '?' + dataStr

 }

 let 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)

 }

 } else {

 onerror()

 }

 }

 xhr.onerror = onerror

 if(type === 'POST'){

 xhr.send(dataStr)

 }else{

 xhr.send()

 }

}

ajax({

 url: '[http://api.xxx.com/weather.php](http://api.xxx.com/weather.php)',

 data: {

 city: '杭州'

 },

 onsuccess: function(res){

 console.log(res)

 },

 onerror: function(){

 console.log('服务器异常')

 }

})
上一篇 下一篇

猜你喜欢

热点阅读