JQuery .load()定义如下:
.load( url [, data] [, complete(responseText, textStatus, XMLHttpRequest)] );
数据和 complete()参数是可选的。对?但是,我们如何称之为:
$('#result').load('ajax/test.html', function(){
alert('Load was performed.');
}
jquery如何忽略第二个参数并知道我们提供了第一个和第三个参数?如果3d参数不是函数怎么办?
答案 0 :(得分:2)
请参阅source code。
load: function( url, params, callback ) {
if (typeof url !== "string" && _load) {
// My comment: the function.apply ia an
// alternative way to call a javascript function,
// where the number of parameter in `arguments`
// couldn't be determined
// the `arguments` is a special javascript variable.
// It's an array containing the parameters within
// the context of a function
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";
}
}
.... other code
答案 1 :(得分:1)
如果使用两个或更多参数调用load
,jQuery将检查第二个参数是函数还是对象。如果它是一个函数,则在ajax
调用完成时调用它。否则,它被用作ajax
调用传递的参数。
来源的相关部分:
if ( params ) {
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = null;
// Otherwise, build a param string
} else if ( typeof params === "object" ) {
params = jQuery.param( params, jQuery.ajaxSettings.traditional );
type = "POST";
}
}
params
是load
的第二个参数。
isFunction
是以下函数的结果:
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
type: function( obj ) {
return obj == null ?
String( obj ) :
class2type[ toString.call(obj) ] || "object";
},
其中class2type
是一个assosiative数组,其中包含此元素:
class2type[ "[object Function]" ] = "function";
答案 2 :(得分:1)
让我们看一下源代码,这样你就会看到第二个参数是否是一个函数,然后将第二个参数params
传递给第三个参数callback
并设置第二个参数params
到undefined
。
// 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";
}
}