【问题标题】:How to serialize a form into an object (with tree structure)?如何将表单序列化为对象(具有树结构)?
【发布时间】:2011-07-16 21:48:23
【问题描述】:

我有一个表格

<form>
    <input type="text" name="Name" />
    <input type="checkbox" name="Feature.Translate" />
    <input type="checkbox" name="Feature.Share" />

    <input type="submit" value="Convert into an object" />
</form>

我想把它转换成一个对象

{
    Name: "John Connor's Terminator",
    Feature:
    {
        Translate: true // if checked
        // Share wasn't checked
    }
}

如何将表单映射到具有这种树结构的对象?

【问题讨论】:

标签: javascript jquery forms


【解决方案1】:

添加此方法以帮助您构建树

// add keys to an object as a tree
// ["a", "b", "c"] will generate
// a { b: { c: def } }
// def is the value of the leaf node
var AddToTree = function(obj, keys, def)
{
    for (var i = 0, length = keys.length; i < length; ++i)
        obj = obj[keys[i]] = i == length - 1 ? def : obj[keys[i]] || {};
};

为 jQuery 选择器创建一个函数,该函数将转换对象中的表单

$.fn.serializeObject = function()
{
   var o = {}; // final object
   var a = this.serializeArray(); // retrieves an array of all form values as
                                  // objects { name: "", value: "" }

   $.each(a, function() {
       var ns = this.name.split("."); // split name to get namespace
       AddToTree(o, ns, this.value); // creates a tree structure
                                     // with values in the namespace
   });

   return o;
};

通过定义这两个函数,您可以在提交按钮上设置一个事件:

$(":submit").click(function(e){
    // contains the object from the form
    // respecting element namespaces
    var obj = $("form").serializeObject();
});

【讨论】:

    【解决方案2】:

    类似下面的东西应该可以工作:

    function serializeData() {
        //this is where we'll store our serialized data
        var serializedData = {};
    
        //iterate over input, select, and textarea elements
        jQuery("input, select, textarea").each(function(index) {
           var $element = jQuery(this);
           var name = $element.attr("name");
    
           //we only want to serialize the element if it has a 'name' attribute
           if(typeof name != "undefined") {
    
              //split on the . to get an array
              var parts = name.split(/\./);
    
              //start building the serialized data
              var currentPart = serializedData;
              for(var i = 0; i < parts.length; i++) {
    
                  //if this particular element doesn't already exist in our hash, create it
                  //and initialize it to an empty hash
                  if(typeof serializedData[parts[i]] == "undefined") {
                      currentPart[parts[i]] = {};
                  }
    
                  //if we're currently looking at the very last element in the array then
                  //it means that we need to set its value to the value of the corresponding
                  //input element. Otherwise, it means that there are still keys within the
                  //array and so we set `currentPart` to the new hash that we just created
                  if(i == parts.length - 1) {
    
                      //if the element is a checkbox or a radio, we need to see if it's checked
                      //instead of looking at its value
                      if($element.attr("type").toLowerCase() == "checkbox" || $element.attr("type").toLowerCase() == "radio") {
                          currentPart[parts[i]] = $element.is(":checked");
                      }
    
                      else {
                         currentPart[parts[i]] = $element.val();
                      }
                  }
    
                  else {            
                      currentPart = currentPart[parts[i]];
                  }                   
              }
           }
        });
    
        console.log(serializedData);
    }
    

    查看fiddle

    您现在需要做的就是将serializeData 绑定到表单上的submit 事件。

    【讨论】:

      猜你喜欢
      • 2014-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-28
      • 1970-01-01
      • 2019-06-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多