Using jQuery load with promises

后端 未结 5 542
夕颜
夕颜 2020-12-09 03:49

I\'m still trying to wrap my head around deferred and what not, so with this in mind I have a question on how to do the following.

My team and I have 3 separate

5条回答
  •  猫巷女王i
    2020-12-09 04:14

    Here's a Gist for a little jQuery plugin that adds a loadThen function to a set of jQuery elements. It's basically load() without the callback and it returns a promise that is only resolved after the content is loaded and inserted into the set of selected elements.

    It's basically a copy/paste of jQuery's own load() code except it returns the promise from the actual ajax call. This lets you get a rejected promise if the ajax fails.

    Since it's based on the load() functionality, you can add a selector after the url seperated by a space to get only a fragment of the loaded html.


    Example 1: Load the home page of this site into element with id="container"

    $('#container').loadThen('/').then(function () {
        // loaded and ready.
    }, function () {
        // error
    });
    

    Example 2: Load the home page's header into this page's header

    $('h1').eq(0).loadThen('/ h1').then(function () {
        // loaded and ready.
    }, function () {
        // error
    });
    

    Gist contents:

    (function ($) {
        var _loadThen = $.fn.loadThen;
        $.fn.loadThen = function (url, params) {
            if (typeof url !== "string" && _loadThen) {
                return _loadThen.apply(this, arguments);
            }
    
            if(this.length <= 0) {
                return jQuery.Deferred().resolveWith(this, ['']);
            }
    
            var selector, type, response,
                self = this,
                off = url.indexOf(" ");
    
            if (off >= 0) {
                selector = jQuery.trim(url.slice(off));
                url = url.slice(0, off);
            }
    
            if (params && typeof params === "object") {
                type = "POST";
            }
    
            return jQuery.ajax({
                url: url,
                type: type,
                dataType: "html",
                data: params
            }).then(function (responseText) {
                    self.html(selector ? jQuery("
    ").append(jQuery.parseHTML(responseText)).find(selector) : responseText); return self; }); }; }(jQuery));

提交回复
热议问题