javascript - Ajax 调用后显示成功消息的问题

标签 javascript php html ajax

我有一个 html 形式,它的数据通过 AJAX 发送 发布到 php 文件。

插入数据库后,我需要向用户显示他刚刚发送的数据已成功插入。

一切正常,但真正的问题是,页面刷新速度太快,我什至看不到消息的内容。

需要考虑的事情:

  1. 之后Ajax call 我对同一页面进行函数调用来刷新它,因为如果没有,页面永远不会刷新。
  2. 我有一个<div>在这个 html 表单,即隐藏的,旨在在服务器响应后隐藏自身。

所以我有两个问题:

  1. 首先,我是怎么做的,有没有更好的方法?
  2. 是否可以使页面刷新后消息持久化?

我留下了一些 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/

相关文章:

javascript - 原型(prototype) javascript 无法正常工作

php - 无法使用 gmail SMTP 从 PHP 发送电子邮件

php - 在php中必须从jquery [object Object]获取数据

php - 使用node.js Node http服务器而不是php/ruby​​/etc + nginx有什么优势?

javascript - 如何在 JSP 中获取特定区域设置的货币符号

Javascript 伪类、jQuery 事件处理程序和 'this'

javascript - 我的输出有什么问题吗?

php - 如何在 JQuery 中打开另一个弹出窗口时自动关闭一个弹出窗口?

html - 悬停后更改背景颜色并保留父图像

javascript - 使用 jquery 更改 HTML 中标签内的文本值