function ajax(options) {
var xhr = new XMLHttpRequest();
var qs = resolveData(options.data)
if (options.method == 'GET') {
xhr.open('GET', options.url + '?' + qs);
xhr.send()
} else if (options.method == 'POST') {
xhr.open('POST', options.url);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
xhr.send(qs)
}
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status == 200) {
var result = JSON.parse(xhr.responseText)
options.success(result)
}
}
function resolveData(data) {
var arr = []
for (var k in data) {
arr.push(k + '=' + data[k])
}
return arr.join('&');
}
}
ajax({
method: 'POST',
url: "http://www.liulongbin.top:3006/api/addbook",
data: {
bookname: '水浒传',
author: '施耐庵',
publisher: '北京图书出版社'
},
success: function (res) {
console.log(res);
}
})