jquery提供的serialize方法能夠?qū)崿F(xiàn)。
$("#searchForm").serialize();
但是,觀察輸出的信息,發(fā)現(xiàn)serialize()方法做的是將表單中的數(shù)據(jù)以htpp請求格式拼接成字符串。
serialize確實是能夠解決一般的提交數(shù)據(jù)。但是有時我們需要的是一個object對象,而不是字符串(比如jqgrid reload時設(shè)置查詢條件參數(shù),就需要object對象)。
方法如下:
(function(window, $) {  $.fn.serializeJson = function() {    var serializeObj = {};    var array = this.serializeArray();    var str = this.serialize();    $(array).each(        function() {          if (serializeObj[this.name]) {            if ($.isArray(serializeObj[this.name])) {              serializeObj[this.name].push(this.value);            } else {              serializeObj[this.name] = [                  serializeObj[this.name], this.value ];            }          } else {            serializeObj[this.name] = this.value;          }        });    return serializeObj;  };})(window, jQuery);調(diào)用:
console.info($("#searchForm").serializeJson());下面通過一段代碼看下jQuery序列化表單為JSON對象
<form id="myform">   <table>     <tr>       <td>姓名:</td>       <td> <input type="text" name="name" /> </td>     </tr>     <tr>       <td>性別:</td>       <td>         <input type="radio" name="sex" value="1"> 男         <input type="radio" name="sex" value="0"> 女       </td>     </tr>     <tr>       <td>年齡:</td>       <td>         <select name="age">           <option value="20">20</option>           <option value="21">21</option>           <option value="22">22</option>         </select>       </td>     </tr>     <tr>       <td>愛好</td>       <td>         <input type="checkbox" value="basketball" name="hobby">籃球         <input type="checkbox" value="volleyball" name="hobby">排球         <input type="checkbox" value="football" name="hobby">足球         <input type="checkbox" value="earth" name="hobby">地球       </td>     </tr>     <tr>       <td colspan="2">         <input type="button" id="ajaxBtn" value="提交" />       </td>     </tr>   </table> </form>  <script type="text/javascript">   $(function() {     $("#ajaxBtn").click(function() {         var params = $("#myform").serializeObject(); //將表單序列化為JSON對象          console.info(params);       })   })   $.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;   } </script>             
新聞熱點
疑難解答
圖片精選