js 使用xmlhttprequest 封装http请求并返回响应的信息,如果超时了,则返回字符串请求超时...-爱代码爱编程
好的,下面是使用XMLHttpRequest对象封装HTTP请求的代码示例,如果请求超时则返回字符串"请求超时":
function httpGet(url, timeout) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.timeout = timeout; // 设置超时时间
xhr.open("GET", url);
xhr.onload = () => {
if (xhr.status === 200) {
resolve(xhr.responseText);
} else {
reject(new Error(xhr.statusText));
}
};
xhr.ontimeout = () => {
reject(new Error("请求超时"));
};
xhr.onerror = () => {
reject(new Error("请求失败"));
};
xhr.send();
});
}