什么是Ajax?

什么是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('服务器异常')

 }

})
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。