我有一个 html
形式,它的数据通过 AJAX
发送 发布到 php
文件。
插入数据库后,我需要向用户显示他刚刚发送的数据已成功插入。
一切正常,但真正的问题是,页面刷新速度太快,我什至看不到消息的内容。
需要考虑的事情:
- 在之后
Ajax
call 我对同一页面进行函数调用来刷新它,因为如果没有,页面永远不会刷新。 - 我有一个
<div>
在这个html
表单,即隐藏的,旨在在服务器响应后隐藏自身。
所以我有两个问题:
- 首先,我是怎么做的,有没有更好的方法?
- 是否可以使页面刷新后消息持久化?
我留下了一些 JS 代码(为了使其简短,因为一切都正常),以及包含 div 的 html 部分:
$('#MiForm').on('submit', function( event )
{
//Creating the necessary instances and data
//Here is where I put different messages for the div "alert"
xhttp.onreadystatechange = function()
{ //Response from the server.
if (xhttp.readyState < 4)
{// Waiting response from server.
document.getElementById('Alert').hidden = false;
document.getElementById('Alert').innerHTML = "Sending Request...";
}
else if (xhttp.readyState === 4)
{// 4 = Response from server has been loaded
if (xhttp.status == 200 && xhttp.status < 300) // (200-299) is succesful.
document.getElementById('Alerta').innerHTML = 'Everything OK!';
}
};
//the Send function and data.
event.preventDefault(); //-->preventing the submit of the normal form cause I use AJAX.
window.location.href = '../Ui/WorkerForm.php' //--->this is where I load the same page where Im on, but it seems that it does it too fast.
});
和 HTML:
<div id="Alert" class="alert alert-success" hidden="true" role="alert"></div>
还有一件事,我向其发送数据的 php 页面不会手动返回任何值,它只是获取数据并调用类来进行插入。
最佳答案
首先,一旦发送 AJAX,您就会刷新页面。 您应该将刷新指令移至 onreadystatechange 函数监听器内,以便在 AJAX 完成后发生,并且您得到响应。
如果这没有帮助,您可以在显示消息和刷新之间添加一个小的定时延迟:
setTimeout(function(){window.location.href = '../Ui/WorkerForm.php';}, TIMEOUT_IN_MILISECONDS);
关于javascript - Ajax 调用后显示成功消息的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35487488/