如何使用JQuery每1秒发送一次Ajax请求?

Dam*_*mir 4 javascript jquery

如何使用JQuery每1秒发送一次Ajax请求?

Mar*_*sen 17

您可能不希望每秒都发送请求,正如大卫已经指出的那样.

因此,使用setInterval是一个坏主意.

而是考虑做这样的事情:

function doAjax() {

  $.ajax({
   ...
   complete: function() {
    setTimeout(doAjax,1000); //now that the request is complete, do it again in 1 second
   }
   ...
  });
}

doAjax(); // initial call will start rigth away, every subsequent call will happen 1 second after we get a response
Run Code Online (Sandbox Code Playgroud)


fel*_*igl 6

你可以使用setInterval,但setInterval不是jQuery的一部分:

setInterval(function() {
    $.get(...);
}, 1000);
Run Code Online (Sandbox Code Playgroud)