Repository navigation
Open
Description
使用原生的XMLHttpRequest实现一个ajax
/**
-
- @param {*} options
- url
- data
- method
- async
- timeout
*/
function ajax(options) {
let url = options.url;
const method = options.method.toLocaleLowerCase() || 'get';
const async = options.async != false; // default is true
const data = options.data;
const xhr = new XMLHttpRequest();
if (options.timeout && options.timeout > 0) {
xhr.timeout = options.timeout;
}
return new Promise((resolve, reject) => {
xhr.ontimeout = () => {reject && reject('请求超时');}
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) { // 请求完成
if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
resolve && resolve(xhr.responseText);
} else {
reject && reject();
}
}
}
xhr.onerror = err => reject && reject(err);
let paramList = [];
let encodeData;
if (data instanceof Object) {
for (let key in data) {
paramList.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
}
encodeData = paramList.join('&');
}
if (method === 'get') {
const index = url.indexOf('?');
if (index === -1) {
url += '?';
} else if (index !== url.length - 1) {
url += '&';
}
url += encodeData;
}
xhr.open(method, url, async);
if (method === 'get') {
xhr.send(null);
} else {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
xhr.send(encodeData);
}
})
}Metadata
Metadata
Assignees
Labels
No labels
Activity
axnir commentedon Nov 16, 2020
options.method.toLocalLowerCase()少了一个字母,toLocaleLowerCase()
louzhedong commentedon Nov 16, 2020
thanks