jQuery使用serialize(),serializeArray()方法取得表單資料+字串和物件類型兩種表單提交的方法

來源:互聯網
上載者:User

標籤:jquery   json   javascript   表單   ajax   

原始form表單值擷取方式(手動):
$.ajax({   type: "POST",   url: "ajax.php",   data: "Name=摘取天上星&position=IT技術",   success: function(msg){alert(msg);},   error: function(error){alert(error);} });
JQ serialize()方法取值:
$.ajax({   type: "POST",   url:"ajax.php",   data:$(‘#formID‘).serialize(),// 要提交的表單   success: function(msg) {alert(msg);},   error: function(error){alert(error);}});
serialize()序列化表單一實例:
<script type="text/javascript" src="jquery-1.9.1.min.js"></script><script type="text/javascript">$(function(){   $("#button").click(function(){     alert($("#formID").serialize());   });});</script><form id="formID">    姓名 <input value="摘取天上星" name="Name" />    職位 <input value="IT技術" name="position" />        <input id="button" value="提交" type="button" /></form>

 將form中的值轉換為索引值對:

// 如:{Name:‘摘取天上星‘,position:‘IT技術‘}// ps:注意將同名的放在一個數組裡function getFormJson(form) {var o = {};var a = $(form).serializeArray();$.each(a, function () {if (o[this.name] !== undefined) {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;}
索引值對方式的AJAX調用:
//調試調用 $(function(){$("#button").click(function(){alert(getFormJson("#formID"));});});//Ajax提交$.ajax({   type: "POST",   url:"ajax.php",   data:getFormJson($("#formID")),//表單資料JSON格式的函數參數裡填寫表單的ID或要提交的表單   dataType: ‘json‘,   success: function(msg) {alert(msg);},   error: function(error){alert(error);}});
執行個體中通用的HTML表單:
<form id="formID">    姓名 <input value="摘取天上星" name="Name" />    職位 <input value="IT技術" name="position" />        <input id="button" value="提交" type="button" /></form>




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.