In the course of web development, it is common to submit a string that does not format the form to the background, which describes how to serialize the form form into a JSON string.
First, it is the extended jquery serialization plugin, which relies on jquery. After testing, this code can be placed in $ (Funciton () {}), can also be placed outside, can achieve the effect.
$.fn.serializeobject =function() { varo = {}; varA = This. Serializearray (); $.each (A,function() { if(o[ This. Name]) { if(!o[ This. Name].push) {o[ This. name] = [o[ This. Name]]; } o[ This. Name].push ( This. value | | ‘‘); } Else{o[ This. Name] = This. value | | ‘‘; } }); returno; };
If the above method cannot be called, you can also do this (I in the actual development, the above method is not used, very tangled, the use of this method):
functionSerializeObject (form) {varn \ {}; varA =$ (form). Serializearray (); $.each (A,function() { if(o[ This. Name]) { if(!o[ This. Name].push) {o[ This. name] = [o[ This. Name]]; } o[ This. Name].push ( This. value | | ‘‘); } Else{o[ This. Name] = This. value | | ‘‘; } }); returno; };
The call is as follows:
function SubmitForm () { var data= serializeobject ("#form1"); Alert (json.stringify (data)); }
If the need is to use the AJAX request, I am using an example on the network, but also good, as follows:
functionAddpersoninfo () {//serializing a form varData = $ (' #personInfo '). SerializeObject (); $.ajax ({type:"POST", DataType:"JSON", URL:"Http://localhost:8080/appname/queryByCondition", Data:JSON.stringify (data), ContentType:"Application/json;charset=utf-8", Success:function(msg) {varNotice =eval (msg); if(notice.type== "Success") {alert (notice.msg); Window.location.href=Notice.data.url; }Else if(notice.type== "Validfail") {$.each (notice.errors,function(index, datavalidmsg) {alert (datavalidmsg.msg); }); }Else if(notice.type= "Fail") {alert (notice.msg); }}, Error:function(msg) {varNotice =eval (msg); alert (notice.msg); } }); }
The above code to give me a lot of help, I hope to write to help more friends, but also easy to access their own reference.
Form forms are serialized as JSON-formatted data