jQuery使用serialize(),serializeArray()方法取得表单数据

原始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()序列化表单实例:

$(function(){
   $("#button").click(function(){
     alert($("#formID").serialize());
   });
});

将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>

原文出处:http://www.2cto.com/kf/201406/306550.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值