获取jQuery $ .load()ajax对象

时间:2011-09-05 04:29:25

标签: jquery ajax abort

正如以下链接所示,jQuery的$ .ajax调用返回一个ajax对象,以后可以在需要时用于中止调用。

Abort Ajax requests using jQuery

我的项目使用$ .load(),它返回对象模式,而不是ajax对象($(“”)。load())。

有没有办法可以从$ .load获取ajax对象?

1 个答案:

答案 0 :(得分:0)

我认为你不能用当前的API做到这一点。但是,感谢开源,请查看load函数的源代码(来自jquery-1.6.2.js):

jQuery.fn.extend({
load: function( url, params, callback ) {
    if ( typeof url !== "string" && _load ) {
        return _load.apply( this, arguments );

    // Don't do a request if no elements are being requested
    } else if ( !this.length ) {
        return this;
    }

    var off = url.indexOf( " " );
    if ( off >= 0 ) {
        var selector = url.slice( off, url.length );
        url = url.slice( 0, off );
    }

    // Default to a GET request
    var type = "GET";

    // If the second parameter was provided
    if ( params ) {
        // If it's a function
        if ( jQuery.isFunction( params ) ) {
            // We assume that it's the callback
            callback = params;
            params = undefined;

        // Otherwise, build a param string
        } else if ( typeof params === "object" ) {
            params = jQuery.param( params, jQuery.ajaxSettings.traditional );
            type = "POST";
        }
    }

    var self = this;

    // Request the remote document
    jQuery.ajax({
        url: url,
        type: type,
        dataType: "html",
        data: params,
        // Complete callback (responseText is used internally)
        complete: function( jqXHR, status, responseText ) {
            // Store the response as specified by the jqXHR object
            responseText = jqXHR.responseText;
            // If successful, inject the HTML into all the matched elements
            if ( jqXHR.isResolved() ) {
                // #4825: Get the actual response in case
                // a dataFilter is present in ajaxSettings
                jqXHR.done(function( r ) {
                    responseText = r;
                });
                // See if a selector was specified
                self.html( selector ?
                    // Create a dummy div to hold the results
                    jQuery("<div>")
                        // inject the contents of the document in, removing the scripts
                        // to avoid any 'Permission Denied' errors in IE
                        .append(responseText.replace(rscript, ""))

                        // Locate the specified elements
                        .find(selector) :

                    // If not, just inject the full result
                    responseText );
            }

            if ( callback ) {
                self.each( callback, [ responseText, status, jqXHR ] );
            }
        }
    });

    return this;
}
}

一个稍微危险但可行的解决方案是复制该源并进行更改,以便它返回ajax调用返回的内容,而不是return this。这很危险,因为它可能依赖于内部jquery行为,这种行为可能会在未来的版本中发生变化,恕不另行通知。

我可能会使用不同名称的新函数扩展jQuery.fn,也许是loadAjax

如果您使用的是不同版本的jquery,请从那里开始使用。