封装一个 ajax 函数,能实现如下方法调用

function ajax(options){
//补全
}
ajax({
url: 'http://api.jirengu.com/weather.php',
data: {
city: '北京'
},
onsuccess: function(ret){
console.log(ret)
},
onerror: function(){
console.log('服务器异常')
}
})


function ajax(opts){
        var url = opts.url
        var type = opts.type || 'GET'
        var dateType = opts.dataType || 'json'
        var onsuccess = opts.onsuccess || function(){}
        var onerror = opts.onerror || function(){}
        var data = opts.data || {}

        var dataStr = []
        for(var key in data) {
            dataStr.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.readystatus === 4&& xhr.status === 200){
                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.jirengu.com/weather.php',
        data: {
            city: '北京'
        },
        onsuccess: function(ret){
            console.log(ret)
        },
        onerror: function(){
            console.log('服务器异常')
        }
    })

你可能感兴趣的:(封装一个 ajax 函数,能实现如下方法调用)