对ajax简单的封装
demo:
function ajax(type,url,data,fn) {
var xhr = new XMLHttpRequest()
type = type.toUpperCase()
if(typeof data === 'object') {
var ary = []
for(var key in data) {
ary.push(key + '=' + data[key])
}
data = ary.join('&')
}
if(type === 'GET') {
url = url + '?' + data;
}
xhr.open(type,url)
var datas = null
if(type === 'POST') {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
datas = data
}
xhr.send(datas)
xhr.onload = function() {
fn(this.response)
}
}
使用:
ajax('get','https://me.csdn.net/weixin_45426836',{
age: 111,
name: 222
},function (result) {
console.log(result)
})
ajax('post','https://me.csdn.net/weixin_45426836',{
age: 333,
name: 444
},function (result) {
console.log(result)
})