在同一页上进行AJAX请求,但是不将其显示出来的解决方法是通过设置AJAX请求的async
属性为false
,或者使用Promise对象来处理AJAX请求。
方法一:设置async
属性为false
var xhr = new XMLHttpRequest();
xhr.open('GET', 'example.com/api/data', false); // 设置async属性为false
xhr.send();
console.log(xhr.responseText); // 在控制台中输出响应结果
方法二:使用Promise对象处理AJAX请求
function ajaxRequest(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onload = function() {
if (xhr.status === 200) {
resolve(xhr.responseText); // 请求成功时调用resolve,并将响应结果作为参数传递
} else {
reject(xhr.statusText); // 请求失败时调用reject,并将错误信息作为参数传递
}
};
xhr.onerror = function() {
reject(xhr.statusText); // 请求出错时调用reject,并将错误信息作为参数传递
};
xhr.send();
});
}
ajaxRequest('example.com/api/data')
.then(function(response) {
console.log(response); // 在控制台中输出响应结果
})
.catch(function(error) {
console.error(error); // 在控制台中输出错误信息
});
以上两种方法都可以在AJAX请求完成后获取到响应结果,但不会将其显示在页面上。