jQuery获取表单数据serialize方法的使用和注意事项
/*获取表单formId下的数据
*/
var formData = $('#formId').serialize();
/*
表单formId下的数据formData最终序列化的结果如下所示:
userName=admin&userAge=22&userMobile=13551369999
*/
/*
需要注意的是jQuery中serialize方法是没有去除表单值两端空格的,
此时需要对源码稍作修改(此jQuery版本以1.9.1为例),具体修改如下:
大概在jQuery1.9.1版本源码的7341行处,可搜索关键字:encodeURIComponent即可找到,
找到后将
s[s.length] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
修改为s[s.length] = encodeURIComponent(key) + "=" + encodeURIComponent(jQuery.trim(value));即可
*/
//Serialize an array of form elements or a set of
//key/values into a query string
jQuery.param = function (a, traditional) {
var prefix,
s = [],
add = function (key, value) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction(value) ? value() : (value == null ? "" : value);
//quber:为serialize方法去除值两边的空格
s[s.length] = encodeURIComponent(key) + "=" + encodeURIComponent(jQuery.trim(value));
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if (traditional === undefined) {
traditional = jQuery.ajaxSettings && 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 (prefix in a) {
buildParams(prefix, a[prefix], traditional, add);
}
}
// Return the resulting serialization
return s.join("&").replace(r20, "+");
};
分享到: