要解决这个问题,可以通过设置一个定时器来延迟隐藏Ajax成功后的提示消息。下面是一个示例代码:
HTML代码:
JavaScript代码:
function ajaxRequest() {
// 创建XMLHttpRequest对象
var xhr = new XMLHttpRequest();
// 设置请求完成后的回调函数
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
// 显示提示消息
document.getElementById("message").style.display = "block";
// 延迟一段时间后隐藏提示消息
setTimeout(function() {
document.getElementById("message").style.display = "none";
}, 3000); // 3秒后隐藏
}
};
// 发送Ajax请求
xhr.open("GET", "ajax.php", true);
xhr.send();
}
在上述代码中,首先在HTML中创建一个id为"message"的元素,用于显示Ajax请求成功的提示消息。然后,在JavaScript中定义了一个ajaxRequest函数,用于发送Ajax请求。
在xhr.onreadystatechange回调函数中,当Ajax请求完成且成功时,通过设置document.getElementById("message").style.display = "block"来显示提示消息。然后,使用setTimeout函数设置一个定时器,延迟3秒后将提示消息隐藏,通过设置document.getElementById("message").style.display = "none"来实现。
这样,当Ajax请求成功后,提示消息会在一段时间后自动隐藏。