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

Problems to show success message after Ajax Call

本文关键字:消息 问题 成功 显示 Ajax 调用      更新时间:2023-09-26

>我有一个html表单,它的数据通过AJAX帖子发送到php文件。

插入

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

一切正常,但真正的问题是,页面刷新得如此之快,以至于我什至看不到消息的内容。

需要考虑的事情:

  1. Ajax调用之后,我对同一页面进行函数调用以刷新它,因为如果没有,页面永远不会刷新。
  2. 我有一个html形式的<div>,它是隐藏的,旨在在服务器响应后取消隐藏自己。

所以我有两个问题:

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

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