只有在ajax请求完全完成后才执行js函数

Execute a js function only after the ajax request fully compleated

本文关键字:执行 函数 js ajax 请求      更新时间:2023-09-26

我想只在jquery ajax调用完全完成后执行js函数。(在成功和错误事件完成后)。在ajax调用后将传入的数据放入元素。

如何做到这一点

你应该使用$.ajaxComplete();

$(document).ajaxComplete(function() {
  alert("compete");
});

将在每次对页面进行Ajax调用后触发

否则使用ajax()并设置完整的属性

$.ajax({
  url: "myurl",
  complete: function(){
              alert("complete");
            }
  //set all the other options as usual

您可以使用任何jQuery AJAX方法的回调来延迟另一个函数的执行,直到请求完成。

的例子:

   $.post('/some/url', somedata, function() {
        // put the code you want to execute on completion here
   });

对于更复杂的场景,使用实际的ajax方法,它为成功、完成、错误和其他事件提供钩子。通常,您只需要成功和错误。

   $.ajax( '/some/url', {
        data: somedata,
        type: 'post',
        success: function(result) {
           // success code execution here
        },
        error: function(xhr,status,error) {
           // error code here
        },
        complete: function(xhr,status) {
           // completion code here
        }
   });

如果您想为一个特定的调用这样做,那么complete函数可能就是您需要的。如果您希望这是全局的,对于所有ajax调用,那么Nicola的答案应该是您所需要的。

这是Ajax调用的jQuery文档