HTML表单转JSON:jquery.serializeJSON

jopen 10年前

支持将一个HTML表单序列化成JavaScript对象,支持嵌套属性和数组。

Usage Example

HTML form (input, textarea and select tags supported):

<form id="my-profile">    <!-- simple attribute -->    <input type="text" name="fullName"              value="Mario Izquierdo" />      <!-- nested attributes -->    <input type="text" name="address[city]"         value="San Francisco" />    <input type="text" name="address[state][name]"  value="California" />    <input type="text" name="address[state][abbr]"  value="CA" />      <!-- array -->    <input type="text" name="jobbies[]"             value="code" />    <input type="text" name="jobbies[]"             value="climbing" />      <!-- and more ... -->    <textarea              name="projects[0][name]">serializeJSON</textarea>    <textarea              name="projects[0][language]">javascript</textarea>    <input type="hidden"   name="projects[0][popular]" value="0" />    <input type="checkbox" name="projects[0][popular]" value="1" checked="checked"/>      <textarea              name="projects[1][name]">tinytest.js</textarea>    <textarea              name="projects[1][language]">javascript</textarea>    <input type="hidden"   name="projects[1][popular]" value="0" />    <input type="checkbox" name="projects[1][popular]" value="1"/>  </form>

JavaScript:

$('#my-profile').serializeJSON();  // returns =>  {    fullName: "Mario Izquierdo",      address: {      city: "San Francisco",      state: {        name: "California",        abbr: "CA"      }    },      jobbies: ["code", "climbing"],      projects: {      '0': { name: "serializeJSON", language: "javascript", popular: "1" },      '1': { name: "tinytest.js",   language: "javascript", popular: "0" }    }  }

项目主页:http://www.open-open.com/lib/view/home/1416145778836