jquery 表单序列化 转换json

function paramString2obj (serializedParams) {
   var obj={};
   function evalThem (str) {
       var attributeName = str.split("=")[0];
       var attributeValue = str.split("=")[1];
       if(!attributeValue){
           return ;
       }
       var array = attributeName.split(".");
       for (var i = 1; i < array.length; i++) {
           var tmpArray = Array();
           tmpArray.push("obj");
           for (var j = 0; j < i; j++) {
               tmpArray.push(array[j]);
           };
           var evalString = tmpArray.join(".");
           if(!eval_r(evalString)){
               eval_r(evalString+"={};");               
           }
       };
       eval_r("obj."+attributeName+"='"+attributeValue+"';");
   };
   var properties = serializedParams.split("&");
   for (var i = 0; i < properties.length; i++) {
       evalThem(properties[i]);
   };
   return obj;
}
$.fn.form2json = function(){
   var serializedParams = this.serialize();
   var obj = paramString2obj(serializedParams);
   return JSON.stringify(obj);
};
 
使用方法
var json = $("#testform").form2json();
alert(json);
   
posted @ 2013-06-20 01:05  weikai  阅读(316)  评论(0编辑  收藏  举报