鍍金池/ 問答/HTML/ 怎么知道ajax 請(qǐng)求完了,想在數(shù)據(jù)沒請(qǐng)求完時(shí),頁面有一個(gè)loading效果

怎么知道ajax 請(qǐng)求完了,想在數(shù)據(jù)沒請(qǐng)求完時(shí),頁面有一個(gè)loading效果

怎么知道ajax 請(qǐng)求完了,想在數(shù)據(jù)沒請(qǐng)求完時(shí),頁面有一個(gè)loading效果,有沒有好的方案

回答
編輯回答
青瓷

原生js XMLHttpRequest在onreadystatechange事件根據(jù)判斷readyState和status的狀態(tài)可以知道數(shù)據(jù)是否已發(fā)送完

2017年10月3日 10:38
編輯回答
嘟尛嘴

參考下

    var loading = (function(){

        var $loading = $('body').append('<div id="loading"></div>');

        var show = function(){
            $loading.fadeIn();
        };

        var hide = function(){
            $loading.fadeOut();
        };

        return {
            show: show,
            hide: hide
        }
    })();

    // 開始發(fā)起ajax調(diào)用
    loading.show();

    $.ajax({
        url: '/path/to/file',
        type: 'default GET (Other values: POST)',
        dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
        data: {param1: 'value1'},
    })
    .done(function() {
        console.log("success");
    })
    .fail(function() {
        console.log("error");
    })
    .always(function() {
        // ajax請(qǐng)求結(jié)束時(shí)調(diào)用
        loading.hide();
        console.log("complete");
    });
2018年4月11日 02:31
編輯回答
老梗

題主用的是 jQuery 吧?根據(jù)文檔,$.ajax 提供一個(gè) complete 回調(diào),在請(qǐng)求完成時(shí)會(huì)調(diào)用,像這樣:

// 開始請(qǐng)求
showLoading()
$.ajax(url, {
  complete: function () {
    // 請(qǐng)求完了
    hideLoading()
  }
})
2017年9月5日 01:23