jquery拼接ajax 的json和字串拼接
阿新 • • 發佈:2019-01-31
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="name"/>
<input name="age" value="age"/>
<button type="submit">提交</button>
</form>
</body>
<script src="../js/jquery-1.11.0.min.js"></script>
<script>
var dataId = $("#myForm input").map(function (){
return($(this).attr("name")+'='+$(this).val());
}).get().join("&");
</script>