美文网首页
序列化form表单数据的N种方式

序列化form表单数据的N种方式

作者: zkzhengmeng | 来源:发表于2019-08-13 10:28 被阅读0次
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>form表单序列化</title>
        <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
    </head>
    <style type="text/css">
        input{
            margin: 10px 0;
            height: 30px;
            outline: none;
            padding-left: 6px;
        }
        label{
            width: 100px;
            display: inline-block;
        }
    </style>
    <body>
        <form action="">
            <label>userName:</label> <input type="text" name="userName" placeholder="请输入用户名"/><br />
            <label>pid:</label><input type="text" name="pid" placeholder="请输入证件号" /><br />
            <label>password: </label><input type="password" name="password" placeholder="请输入密码" /><br />
            <label>address:</label><input type="text" name="address" placeholder="请输入地址" /><br />
        </form>
        <button class="str">序列化成字符串</button>
        <button class="objson">序列化成json对象</button>
        <button class="serializeJson">序列化成自定义方法</button>
        <script type="text/javascript">
            $(document).ready(function(){
              // 1.序列化为字符串  结果为 userName=111&pid=1112231&password=wsd&address=qazxsw
             //会出现中文乱码问题原因: .serialize()自动调用了encodeURIComponent方法将数据编码了
             //解决方法:调用decodeURIComponent(XXX,true);将数据解码
              $(".str").click(function(){
                  var strCent = $("form").serialize();
                  strCent =  decodeURIComponent(strCent,true);//解决中文乱码问题decodeURIComponent
                  console.log(strCent)
              });
                // 2.序列化为对象数组    结果为  [{"name":"userName","value":"王明"},{"name":"pid","value":"11222"}]
              $('.objson').click(function(){
                  var arr = $("form").serializeArray();
                  console.log(arr)
              })
               //3.序列化为key:value形式json对象   结果为  {userName: "王明", pid: "123", password: "sxcde", address: "河南周口"}
              $('.serializeJson').click(function(){
                  var objCent = $("form").serializeObject();
                  console.log(objCent)
              })
              
              jQuery.prototype.serializeObject = function(){ //在jq原型上添加serializeObject方法
                  var obj = new Object(); 
                  $.each(this.serializeArray(),function(index,param){ 
                      if(!(param.name in obj)){ 
                          obj[param.name] = param.value; 
                      } 
                  }); 
                  return obj; 
              };            
            });
        </script>
    </body>
</html>

相关文章

网友评论

      本文标题:序列化form表单数据的N种方式

      本文链接:https://www.haomeiwen.com/subject/exomjctx.html