function ajax(options) {
var arr = [];
var str = ‘’
for (var k in options.data) {
str = k + ‘=’ + options.data[k]
arr.push(str)
}
var strReturn = arr.join("&")
//得到data数组转为原始数据格式
var xhr = new XMLHttpRequest();
if (options.method.toUpperCase() === ‘GET’) {
xhr.open(options.method, options.url + ‘?’ + strReturn)
xhr.send();
} else if (options.method.toUpperCase() === ‘POST’) {
xhr.open(options.method, options.url);
xhr.setRequestHeader(‘Content-Type’, ‘application/x-www-form-urlencoded’);
xhr.send(strReturn);
}
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var res = JSON.parse(xhr.responseText)
console.log(res);
options.success(res)
}
}
}
ajax({
method: 'post',
url: 'http://www.liulongbin.top:3006/api/addbook',
data: {
bookname: '拾荒记',
author: 'jack',
publisher: '北京图书出版社'
},
success: function(res) {
console.log(res)
}
})
ajax({
method: 'get',
url: 'http://www.liulongbin.top:3006/api/getbooks',
data: {
id: 1
},
success: function(res) {
if (res.status === 200) {
alert('成功')
}
}
})