首頁  >  文章  >  web前端  >  form轉json實作方法

form轉json實作方法

小云云
小云云原創
2018-01-26 09:46:011595瀏覽

本文主要介紹了jQuery實現的form轉json功能,結合完整實例形式分析了jQuery將form表單資料封裝成json傳輸的具體步驟與相關操作技巧,需要的朋友可以參考下,希望能幫助到大家。


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="application/javascript" src="js/jquery-2.0.3.js"></script>
<title>无标题文档</title>
<script type="application/javascript">
$.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 || &#39;&#39;);
    } else {
      o[this.name] = this.value || &#39;&#39;;
    }
  });
  return o;
};
function onClik(){
    //var data = $("#form1").serializeArray(); //自动将form表单封装成json
    //alert(JSON.stringify(data));
    var jsonuserinfo = $(&#39;#form1&#39;).serializeObject();
    alert(JSON.stringify(jsonuserinfo));
}
</script>
</head>
<body>
<form id="form1" name="form1" method="post" action="">
 <p>进货人 :
  <label for="name"></label>
  <input type="text" name="name" id="name" />
 </p>
 <p>性别:
  <label for="sex"></label>
  <select name="sex" size="1" id="sex">
   <option value="1">男</option>
   <option value="2">女</option>
  </select>
 </p>
 <table width="708" border="1">
  <tr>
   <td width="185">商品名</td>
   <td width="205">商品数量</td>
   <td width="296">商品价格</td>
  </tr>
  <tr>
   <td><label for="pro_name"></label>
    <input type="text" name="pro_name" id="pro_name" /></td>
   <td><label for="pro_num"></label>
    <input type="text" name="pro_num" id="pro_num" /></td>
   <td><label for="pro_price"></label>
    <input type="text" name="pro_price" id="pro_price" /></td>
  </tr>
  <tr>
   <td><input type="text" name="pro_name2" id="pro_name2" /></td>
   <td><input type="text" name="pro_num2" id="pro_num2" /></td>
   <td><input type="text" name="pro_price2" id="pro_price2" /></td>
  </tr>
 </table>
 <p> </p>
 <input type="button" name="submit" onclick="onClik();" value="提交"/>
</form>
</body>
</html>

程式碼效果示範:

#相關推薦:

在Javascript操作JSON對象,增加刪除修改的簡單實作

JS將string字串轉為json物件的方法

jQuery各種遍歷陣列及json物件的實例程式碼總結

以上是form轉json實作方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn