ajax的简单封装

2017-11-06  本文已影响5人  DCbryant
const ajax = (options) => {
    let url = options.url
    let type = options.type || 'GET'
    let dataType = options.dataType || 'json'
    const onsuccess = options.onsuccess || function(){}
    const onerror = options.onerror || function(){}
    const data = options.data || {}

    const dataStr = []
    for(let key in  data){
        dataStr.push(key + '=' + data[key])
    }
    dataStr = dataStr.join('&')

    if(type === 'GET'){
        url += '?' + dataStr
    }

    const xhr = new XMLHttpRequest()
    xhr.open(type,url,true)
    xhr.onload = () => {
        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: 'https://cn.bing.com/',
    data: {
        city: '武汉'
    },
    onsuccess: function(result){
        console.log(result)
    },
    onerror: function(){
        console.log('服务器异常')
    }
})
上一篇 下一篇

猜你喜欢

热点阅读