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); 这里,我将多选的值封装为一个数值来进行处理。如果大家使用的时候需要将多选的值封装为“,”连接的字符串或者其他形式,请自行修改相应代码。测试如下:表单:Html代码<form id=”myForm” action=”#”> <input name=”name”/> <input name=”age”/> <select multiple=”multiple” name=”interest” size=”2″> <option value =”interest1″>interest1</option> <option value =”interest2″>interest2</option> <option value=”interest3″>interest3</option> <option value=”interest4″>interest4</option> </select> <input type=”checkbox” name=”vehicle” value=”Bike” /> I have a bike <input type=”checkbox” name=”vehicle” value=”Car” /> I have a car <input type=”submit”/> </form> 测试结果:{age: “aa”,interest: ["interest2", "interest4"],name: “dd”,vehicle:["Bike","Car"]}<form id="myForm" action="#"> <input name="name" value="111"/> <input name="age" value="2222"/> <button type="submit">tijiao</button></form></body><script src="../js/jquery-1.11.0.min.js"></script><script> var dataId = $("#myForm input").map(function (){ // return($(this).attr("id")); return($(this).attr("name")+'='+$(this).val()); }).get().join("&"); alert(dataId); </script>新闻热点
疑难解答