form表單序列化為json格式數據


在web開發過程中,經常遇到將form序列化不能格式的字符串提交到后台,下面就介紹怎樣將form表單序列化為json字符串。

首先,是擴展的jquery序列化插件,依賴jquery。經測試,這段代碼可以放在$(funciton(){})中,也可以放在外面,都可以實現效果。

$.fn.serializeObject = function()
        {
           var o = {};
           var a = 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 || '';
               }
           });
           return o;
        };

如果上面的方法不能調用,還可以這樣做(本人在實際開發中,上面方法使用不了,甚是糾結,就采用了此法):

function serializeObject(form)
        {
           var o = {};
           var a = $(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 || '';
               }
           });
           return o;
        };

調用如下:

function submitForm(){
            var data= serializeObject("#form1");
            alert(JSON.stringify(data));
        }

如果需要是使用ajax請求的化,本人是用網絡上的一個例子,也不錯,如下:

function addPersonInfo(){  

   //序列化form

    var data = $('#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) {

    var notice = 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) {

       var notice = eval(msg);

    alert(notice.msg);

    }

    }); 

}

上面的代碼給我很多幫助,希望寫出來可以幫助更多的朋友,同時也方便自己查閱借鑒。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM