使用jQuery Ajax添加加载和错误文本

Adding in loading and error text with jQuery Ajax

本文关键字:错误 文本 加载 添加 jQuery Ajax 使用      更新时间:2023-09-26

我想知道如何容易是扩展这段代码,使它显示一个错误,如果它不能连接,而它正在连接它显示加载文本或加载图像。在ajax驱动的网站上,这似乎是相当标准的行为,但我还没有在网上找到很多关于如何实现它的有用信息。

$(document).ready(function () {
var loadUrl = 'http://sheldonbrown.com/web_sample1.html';
    $("#close").click(function () {
        $("#country_slide").hide();
    });
    $("#country").click(function () {
        $("#country_slide").show();
        $("#country_slide").html(ajax_load).load(loadUrl);
    });
});

根据应用程序的上下文,您可以订阅回调以触发某些全局 AJAX事件。例如,每当AJAX调用开始时,或者AJAX调用抛出错误时。

$(document)
    .ajaxStart(function (e) {
        $('body').showMyAwesomeLoadingGIF();
    })
    .ajaxComplete(function (e) {
        $('body').hideMyAwesomeLoadingGIF();
    });

这将导致这两个回调函数在适当的生命周期事件中触发文档中的每个AJAX调用。

如果出于某种原因,您希望某个AJAX调用而不是触发全局AJAX事件处理程序,您可以指定该特定AJAX调用为而不是全局

$.ajax({
    global : false,
    // blah
})

关于全局AJAX事件处理的更多信息请点击这里。

编辑

如果您想要保持更细粒度的控制,有$.ajaxSetup(),但由于jQuery本身不鼓励使用它,我认为您可能不得不设计自己的解决方案。

就我个人而言,如果您希望重复执行自定义选项值,我会使用带闭包的包装器函数来设置自定义选项值。

var ajax = (function () {
    var defaults = { };
    return function (opts) {
        opts = $.extend({}, defaults, opts);
        // place what you want to happen when an AJAX call starts here
        return $.ajax(opts)
            // place corresponding events here
            .done(function (m) {
            })
            .fail(function (x,s,e) {
            })
            .complete(function (m) {
            });
    };
}());
// then use that in your code like how you'd use $.ajax():
ajax({
    url : 'http://my.domain.com/api/users',
    type : 'GET'
}).done(function (m) {
    console.log('Done GET users.');
});
// ... and you can be sure that it has default options and default event handlers,
//     while being able to add on to them if you wish.