简体   繁体   English

在等待 ajax 请求完成时运行函数

[英]Running a function while waiting for ajax request to complete

I am trying to solve a problem I have and I am a bit stuck with how to do this.我正在尝试解决我遇到的一个问题,但我对如何做到这一点有些困惑。

I am currently posting to my PHP page via AJAX, and while I am waiting for the request to respond I am wanting to run a function that simply displays loading.. and adds an additional '.'我目前正在通过 AJAX 发布到我的 PHP 页面,在等待请求响应时,我想运行一个仅显示加载的函数。并添加一个额外的 '.' every 100ms.每 100 毫秒。 My problem is How can I call a function and then 'stop' that function when my ajax request has completed?我的问题是如何在我的 ajax 请求完成后调用一个函数然后“停止”该函数?

I have tried some promise based code but I want to know what is the best approach to do what I am trying to do?我尝试了一些基于 Promise 的代码,但我想知道做我想做的事情的最佳方法是什么?

$.ajax({
  type: "POST",
  url: "controllers/register.php",
  data: $("form").serialize(),
  beforeSend:() => {
    // Start LoadingBar() Here.
  },
  success:() => {
    // Stop LoadingBar() Here.
  }
})

function LoadingBar() {
  let elem = document.getElementById('para');
  elem.innerHTML += "Loading ."

  setInterval(() => {
    elem.innerHTML += " ."
  }, 100);
}

Any help or any direction on where I can find the information to figure this out would be much appreciated.任何有关我在哪里可以找到解决此问题的信息的帮助或任何指示都将不胜感激。

Use this approach: it will dispaly a gif spinner or loader on every ajax call on that page, so just add this function on your js file and give the path to that image.使用这种方法:它会在该页面上的每个 ajax 调用上显示一个 gif 微调器或加载器,因此只需在您的 js 文件中添加此函数并提供该图像的路径。

  // Add Loader on every ajax calls
        $("body").once('body').prepend("<div id='spinner-amt'><img src='/assets/images/spinner.gif'></div>");
        $(document).ajaxSend(function(){
          $('#spinner-amt').show();
        });
        $(document).ajaxComplete(function(){
          $('#spinner-amt').hide();
        });

and if you want to design the loader, just add the following css to youe css file.如果你想设计加载器,只需将以下 css 添加到你的 css 文件中。 following css will show the spinner the middle of the page.以下 css 将在页面中间显示微调器。

#spinner-amt {
  width: 100%;
  position: fixed;
  z-index: 99999;
  height: 100%;
  text-align: center;
  padding-top: 45vh;
}
 let elem = document.getElementById('para');
  elem.innerHTML += "Loading ."

    $.ajax({
      type: "POST",
      url: "controllers/register.php",
      data: $("form").serialize(),

      success:() => {
 let elem = document.getElementById('para');  
 elem.innerHTML += " ."

      },
error:() => {
          let elem = document.getElementById('para');  
         elem.innerHTML += " ."
          }
    })

before calling ajax call all loading to inner HTML and on success or error remove it在调用 ajax 之前调用所有加载到内部 HTML 并在成功或错误时删除它

You are close.你很近。 Now simply use clearInterval in the success callback to stop the function once the request is complete.现在只需在成功回调中使用clearInterval即可在请求完成后停止该函数。 Also, avoid mixing vanilla JS with JQuery.另外,避免将 vanilla JS 与 JQuery 混合使用。

Here's a working JSFiddle based on your code so you can see it in action.这是一个基于您的代码的有效JSFiddle ,因此您可以看到它的运行情况。

function LoadingBar() {
  $('#para').html('Loading .');

  loading = setInterval(() => {
    $('#para').append(" .");
  }, 100);
}

$(function() {
  $.ajax({
    type: "POST",
    url: "controllers/register.php",
    data: $("form").serialize(),
    beforeSend: () => {
      LoadingBar();
    },
    success: (data) => {
      clearInterval(loading);
      $('#para').html(data);
    }
  });
});

How can I call a function and then 'stop' that function when my ajax request has completed?当我的 ajax 请求完成时,如何调用一个函数然后“停止”该函数?

Use setInterval to add the dots to your progress bar, then clear the returned handle with clearTimeout when the request completes.使用setInterval将点添加到进度条,然后在请求完成时使用clearTimeout清除返回的句柄。

Here's a simple example just using a callback (assumes jQuery).这是一个仅使用回调的简单示例(假设为 jQuery)。 The cool kids use either promises or async/await nowadays, but it all the same under the hood.现在酷孩子们要么使用 promises,要么使用 async/await,但在幕后都是一样的。

function load() {
  // Start the animation.
  $('#results').hide();
  $('#progress-bar').show();

  const timeoutHandle = setInterval(incrementProgress, 100);

  fakeRequest(function successCallback() {
    // When the request is done...

    // 1. Clean up the animation timer.
    clearTimeout(timeoutHandle);

    // 2. Display results and hide the animation.
    $('#progress-bar').hide();
    $('#results').show();
  });
}

function incrementProgress() {
  $('#progress-bar').get(0).innerHTML += '.';
}

function fakeRequest(callback) {
  // This doesn't actually load data.
  // Launch your ajax request instead.
  setTimeout(callback, 1000);
}

fiddle小提琴

Use clearInterval .使用clearInterval

Example:例子:

let intervalId;

$.ajax({
  type: "POST",
  url: "controllers/register.php",
  data: $("form").serialize(),
  beforeSend:() => {
    startLoading();
  },
  success:() => {
    stopLoading();
  }
})

function startLoading() {
  let elem = document.getElementById('para');
  elem.innerHTML += "Loading ."

  intervalId = setInterval(() => {
    elem.innerHTML += " ."
  }, 100);
}

function stopLoading() {
  clearInterval(intervalId);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM