const ajax = option => {
const objToString = data => {
data.t = new Date().getTime();
let res = [];
for (let key in data) {
res.push(encodeURIComponent(key) + ' = ' + encodeURIComponent(data[key]));
}
return res.join('&');
};
let str = objToString(option.data || {});
var xmlHttp, timer;
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else if (xmlHttp) {
xmlHttp = new ActiveXObject('Microsoft.xmlHttp');
}
if (option.type.toLowerCase() === 'get') {
xmlHttp.open(option.type, option.url + '?t=' + str, true);
xmlHttp.send();
} else {
xmlHttp.open(option.type, option.url, true);
xmlHttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlHttp.send(str);
}
xmlHttp.onreadystatechange = function () {
clearInterval(timer);
if (xmlHttp.readyState === 4) {
if ((xmlHttp.status >= 200 && xmlHttp.status < 300) || xmlHttp.status == 304) {
option.success(xmlHttp.responseText);
} else {
option.error(xmlHttp.responseText);
}
}
};
if (option.timeout) {
timer = setInterval(function () {
xmlHttp.abort();
clearInterval(timer);
}, option.timeout);
}
};
调用
ajax({
type: 'GET',
url: 'http://localhost:3000/posts',
timeout: 1000,
success: data => {
console.log('success', data);
},
error: err => {
console.log('error', err);
},
});
json-server 创建模板数据
{ "posts": [ { "id": 1, "title": "json-server", "author": "xianzao" } ], "comments": [ { "id": 1, "body": "some comment", "postId": 1 } ], "profile": { "name": "xianzao" }}启动 npx json-server .\data\data.json