整理文档,搜刮出一个jquery拼接ajax 的json和字符串拼接的代码,稍微整理精简一下做下分享。jQuery拼接字符串ajax<form id="myForm" action="#">
<input name="name"/>
<input name="age"/>
<input type="submit"/>
</form>
<script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
(function($){
$.fn.serializeJson=function(){
var serializeObj={};
$(this.serializeArray()).each(function(){
serializeObj[this.name]=this.value;
});
return serializeObj;
};
$('#myForm').bind('submit',function(e){
console.log($(this).serializeJson())
})
})(jQuery)
</script>或者直接用$(“#表单id”).serialize()直接序列化。。。上面的插件,不能适用于有多个值的输入控件,例如复选框、多选的select。下面,我将插件做进一步的修改,让其支持多选。代码如下:Js代码(function($){
$.fn.serializeJson=function(){
var serializeObj={};
var array=this.serializeArray();
var str=this.serialize();
$(array).each(function(){
if(serializeObj[this.name]){
if($.isArray(serializeObj[this.name])){
serializeObj[this.name].push(this.value);
}else{
serializeObj[this.name]=[serializeObj[this.name],this.value];
}
}else{
serializeObj[this.name]=this.value;
}
});
return serializeObj;
};
})(jQuery);
更多相关内容: