jquery擴展方法(表單數據格式化為json對象)


1、jquery擴展方法(表單數據格式化為json對象)

<script type="text/javascript">
// 將表單數據序列化為一個json對象,例如 {"name":"zs", "age":10}
// 使用:var jsonObj = $("#formId").serializeObject();
$.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>

 

2、jquery的表單序列化方法

  (1)$("#formId").serialize(): 將所有表單選中項拼接成形如"username=zs&password=123"的字符串

  (2)$("#formId").serializeArray(): 將表單所有選中項拼成json數組,格式為:

    [{name: "username", value: "zs"},{name: "password", value: "123"}]

  (3)$.param(jsonObj): 將json對象轉換成形如"username=zs&password=123"的字符串

 

3、案例

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://code.jquery.com/jquery-1.12.4.min.js"></script>
</head>
<body>
    <h2>a頁面</h2>
    <form id="form">
        <input type="text" name="username"/>
        <input type="text" name="password"/>
        <input type="button" value="submit" onclick="formSubmit()"/>
    </form>
</body>

<script type="text/javascript">
    function formSubmit() {
        var str = $("#form").serialize();
        console.log(str);
        var jsonArray = $("#form").serializeArray();
        
        console.log(jsonArray);
        console.log(jsonArray[0].name);
        console.log(jsonArray[0].value);
        console.log(jsonArray[1].name);
        console.log(jsonArray[1].value);
        
        var jsonObj = $("#form").serializeObject();
        console.log(jsonObj);
        console.log(jsonObj.username + "---" + jsonObj.password);

     var str = $.param(jsonObj);
        console.log(str); }
</script> <script type="text/javascript"> // 將表單數據序列化為一個json對象,例如 {"name":"zs", "age":10} // 使用:var jsonObj = $("#formId").serializeObject(); $.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> </html>

 

  結果:

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM