获取jQuery $ .load()ajax对象
问题描述:
正如以下链接所示,jQuery的$ .ajax调用返回一个ajax对象,稍后可用于在需要时中止该调用。
Abort Ajax requests using jQuery
我的项目是使用$ .load(),它返回对象的模式,而不是Ajax对象($( “”)。load()方法)。
有没有办法从$ .load获得ajax对象?
答
我不认为你可以用当前的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,把它从那里。
为什么你不能改变使用$ .ajax,所以你可以使用相同的方法? – momo
我有一个使用$ .load()的项目,将$ .load()更改为$ .ajax()不是一个好主意。如果$ .load()可以以某种方式返回jqXHR对象来取消请求,那将会很好。 – Mumzee