jquery splicing json of ajax and string splicing method
- 2021-08-03 08:58:00
- OfStack
Organize the documents, search out an jquery splicing ajax json and string splicing code, and slightly organize and simplify 1 to share.
jQuery Splice String 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>
Or serialize directly with $("# Form id"). serialize (). . .
The above plug-in cannot be applied to input controls with multiple values, such as check boxes, multi-selected select. Next, I will make a step one modification to make it support multiple choices. The code is as follows:
Js code
(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);
Here, I encapsulate the multi-selected value as a numeric value for processing. If you need to encapsulate the multi-selected values as "," connected strings or other forms, please modify the corresponding code.
The tests are as follows:
Form:
Html code
<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>
Test results:
{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>