我听说当我使用jQuery.ajax并将数据作为对象发送时 - 它会自动逃脱字符。
它写在哪里? 我没有在Documentation
中找到它是真的吗?
答案 0 :(得分:1)
在源代码中,定义了本地函数add
:
add = function( key, value ) {
value = jQuery.isFunction( value ) ? value() : value;
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
此函数通过转义特殊字符来准备任何输入。当一个对象作为参数传递时,调用buildParams
方法,传递刚刚定义的add
函数:
for ( var prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
在递归函数 buildParams
中,为每个object-parameter调用add
方法。口味不同,但通常采用以下格式:
add( prefix, obj );
<小时/> 相关代码,源自 the source code :
// Serialize an array of form elements or a set of
// key/values into a query string
param: function( a, traditional ) {
var s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : value;
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( var prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
}
});
function buildParams( prefix, obj, traditional, add ) {
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// If array item is non-scalar (array or object), encode its
// numeric index to resolve deserialization ambiguity issues.
// Note that rack (as of 1.0.0) can't currently deserialize
// nested arrays properly, and attempting to do so may cause
// a server error. Possible fixes are to modify rack's
// deserialization algorithm or to provide an option or flag
// to force array serialization to be shallow.
buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && obj != null && typeof obj === "object" ) {
// Serialize object item.
for ( var name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
答案 1 :(得分:1)
这是隐含的假设。
通常,只要您有一个从对象或参数传输数据的函数,就可以假设该函数将正确地转义/参数化数据,以便您可以传递任意字符串。
假设您正在使用编写良好的库(jQuery是这样的),您应该只需要在显式构建字符串时转义。
例如,jQuery的text()
函数将自动HTML转义文本。