代码&优雅着&生活

导航

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);

    }

    }); 

}

上面的代码给我很多帮助,希望写出来可以帮助更多的朋友,同时也方便自己查阅借鉴。

 

posted on 2015-06-18 23:40  幸运的凌人  阅读(4138)  评论(0编辑  收藏  举报