js序列化封裝成一個對象,以索引值對的方式

來源:互聯網
上載者:User

標籤:inpu   add   分享   doctype   ima   oct   idt   type   char   

js序列化封裝成一個對象,以索引值對的方式

類似:Object   {ni: "1", wo: "2", ta: "3", huge: "4", jindong: "5"…}

jquery的serialize()方法,得到等值的方式

類似:"ni=1&wo=2&ta=3&huge=4&jindong=5&liukaiwei=6"

jquery的serializeArray()方法,得到一個對象裡面有N個對象,每一個索引值對都是以對象形式存在

類似:[Object, Object, Object, Object, Object, Object]  每個對象是以索引值對存在{ "name" : "ni"  , "value" : "1"   }

html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
html,body{font-size: 14px;color: #555555;font-family: "微軟雅黑";}
*{padding: 0px;margin: 0px;}
ul,li{list-style: none;}
a{text-decoration: none;}
form{margin: 50px auto 0px;width: 500px;}
form ul li{margin: 10px 0px;}
input{margin-right: 10px;}
</style>
</head>
<body>
  <form id="form">
    <ul>
      <li><input type="text" name="ni"/><label>你</label></li>
      <li><input type="text" name="wo"/><label>我</label></li>
      <li><input type="text" name="ta"/><label>他</label></li>
      <li><input type="text" name="huge"/><label>胡歌</label></li>
      <li><input type="text" name="jindong"/><label>靳東</label></li>
      <li><input type="text" name="liukaiwei"/><label>劉愷威</label></li>
    </ul>
    <button type="button" id="submit">提交</button>
  </form>
</body>

</html>

JS

 

<script type="text/javascript" src="js/jquery-1.7.2.min.js" ></script>
<script type="text/javascript">
//表單序列化外掛程式
(function($){
  $.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;
  };
})(jQuery);
//form序列化
$("#submit").click(function(){
var jsSerialize=$("#form").serializeObject();                             //js封裝
var jquerySerialize=$("#form").serialize();                                //jquery的serialize()方法
var jquerySerializeArray=$("#form").serializeArray();              //jquery的serializeArray()方法
});

</script>

 附   可以向這個對象中添加新的索引值對,有多種方法添加

 

jsSerialize.tao="7";
var name2="Dong";
jsSerialize[name2]="8";

 

js序列化封裝成一個對象,以索引值對的方式

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.