在Web开发中,处理网络请求是家常便饭。对于JavaScript开发者来说,判断一个href请求是否成功是基本技能。本文将详细介绍如何使用XMLHttpRequest和Fetch API来判断href请求是否成功,包括检查状态码、响应头和响应体。
使用XMLHttpRequest
XMLHttpRequest(XHR)是HTML5中用于在后台与服务器交换数据的对象。以下是使用XHR发起GET请求并判断请求是否成功的步骤:
1. 创建XMLHttpRequest对象
var xhr = new XMLHttpRequest();
2. 设置请求类型、URL和异步处理
xhr.open('GET', 'http://example.com', true);
3. 设置请求完成的回调函数
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) { // 请求已完成
if (xhr.status === 200) { // 状态码为200表示成功
console.log('请求成功');
} else {
console.log('请求失败,状态码:' + xhr.status);
}
}
};
4. 发送请求
xhr.send();
完整示例
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log('请求成功');
} else {
console.log('请求失败,状态码:' + xhr.status);
}
}
};
xhr.send();
使用Fetch API
Fetch API提供了更强大、更灵活的接口来处理网络请求。以下是使用Fetch API发起GET请求并判断请求是否成功的步骤:
1. 使用Fetch API发起请求
fetch('http://example.com')
.then(response => {
if (response.ok) { // response.ok为true时表示状态码在200-299之间
console.log('请求成功');
} else {
console.log('请求失败,状态码:' + response.status);
}
})
.catch(error => {
console.log('请求失败,错误信息:' + error.message);
});
完整示例
fetch('http://example.com')
.then(response => {
if (response.ok) {
console.log('请求成功');
} else {
console.log('请求失败,状态码:' + response.status);
}
})
.catch(error => {
console.log('请求失败,错误信息:' + error.message);
});
总结
本文详细介绍了使用XMLHttpRequest和Fetch API判断href请求是否成功的方法。在实际开发中,你可以根据需求选择合适的方法。希望本文能帮助你更好地掌握JavaScript网络请求的处理技巧。
