在 ajax 微调器显示方面需要帮助



我正在发出一个ajax请求,实际上看起来像这样。

$loading = $("#loadingDiv")
function loadBuildList() {
    $.ajax({
    async:true,
    url:"ajax_test.php",
    beforeSend : function() { $loading.show(); },
    success : function() { $loading.hide() }
    });
}

现在,我需要在 ajax 运行时显示一个微调器图像,此外,在 ajax 的执行结束之前,我的代码不应该进一步执行。如果我做async:false我将无法加载微调器。如果我做了async:true我将无法等到 ajax 执行结束。

以下是我如何调用函数loadBuildList

...
//$loading.show(); // this I will use when aync : false
loadBuildList()
//$loading.hide();
...

我该如何处理这种情况?有人可以帮我解决这个问题吗?

你永远不应该使用 async:false ,否则你会停止整个执行线程,直到它得到响应。

异步

执行后需要运行的所有内容,在本例中$.ajax都需要写入回调中。这就是JQuery $.ajax的内部成功。

$loading = $("#loadingDiv")
function loadBuildList() {
    $.ajax({
    async:true,
    url:"ajax_test.php",
    beforeSend : function() { $loading.show(); },
    success : function() { 
      $loading.hide();
      // Stuff after $.ajax goes here.
    },
    fail: function() {
      // Or here.
    }
    });
}

您还应该阅读如何从异步调用返回响应?

根据您提供的代码片段,似乎没有必要使用beforeSend,因为您在页面上只有一个调用。您可以按照以下方式进行操作。

$loading = $("#loadingDiv");
function loadBuildList() {
    $loading.show(); // Show spinner before AJAX call
    $.ajax({
        async:true,
        url:"ajax_test.php",
        // beforeSend : function() {  },
        success : function() { $loading.hide() }
    });
}

您仍然可以尝试按照@zurfyx所述进行,但通常当您需要集中式内容而不是单个 AJAX 调用时,会遵循这种做法。

处理微调器可以.complete(因此可以同时选择成功和错误):

function loadBuildList() {
    var loading = $("#loadingDiv")
    loading.show();
    $.ajax({
        url:"ajax_test.php",
        complete : function() { loading.hide() }
    });
}

不过,这个评论更有趣:

我的代码不应该进一步执行

不是你不想进一步执行,而是你想在 ajax 调用完成后继续执行。

您可以通过返回 $.ajax 对象来执行此操作,这是一个promise 。 有了承诺,您就可以在自己的代码中添加链调用。 这类似于使用回调参数,但通常更灵活:

function loadBuildList() {
    return $.ajax({
    ...
}
// calling code
loadBuildList().done(function() {
    // code to run when the list has loaded
});

最新更新