ajax完成后,如何显示加载图标

how can I show my loading icon after my ajax is finished

本文关键字:显示 加载 图标 何显示 ajax      更新时间:2023-09-26

我有一个简单的javascript函数,比如:

function showHint() {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            //extract data here
        }
    }
    xmlhttp.open("GET", "articles.php?q=" + cat + "&year1=" + start_year + "&year2=" + end_year, true);
    xmlhttp.send();
}

我希望能够在ajax完成后显示我的加载图标。我在js的一开始就使用显示我的加载图标

$.mobile.loading("show");

它很好地显示了图标(使用jquerymobile)。然而,我只需要在ajax完全完成后隐藏图标。我试过在jQuery中这样使用.done(),但我认为我没有正确使用它:

xmlhttp.onreadystatechange.done(function(){
    $.mobile.loading("hide");
});

您需要使用它的onreadystatechange回调函数。

xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState == 4) {
         $.mobile.loading("hide");
    }
}

因为您已经在使用jquery了。您可以像一样简单地使用jQuery.get()

$.mobile.loading("show");
$.get("articles.php?q=" + cat + "&year1=" + start_year + "&year2=" + end_year, function(data) {
    //Do something
}).done(function() {
    $.mobile.loading("hide");
});