日期:2014-05-16  浏览次数:20774 次

ajax提交form表单

jquery本身是没有提交form表单的方法的,但是如果为了提交一个form而引入一个几十k或者几百K的框架的话又没有那个必要,这里我们就使用的原理就是将form表单中得所有控件拼接成name和value组成的键值对的集合然后通过$.ajax提交数据,当提交form表单时实际上是发了一个简单的ajax请求,只不过请求的数据是通过遍历form中得所有元素得到的。

//调用ajaxSubmit函数提交表单

function subProductForm(url){
    ajaxSubmit(url,$('#product_xx_form'), function(r){
        alert(r);
    });
 }

//将form转为AJAX提交
 function ajaxSubmit(url,frm,fn) {
  var dataPara = getFormJson(frm);
  $.ajax({
   url: url,
   type: 'post',
   data: dataPara,
      async:false, 
      dataType:'text',
   success: fn
  });
 }

//将form中的值转换为键值对。
 function getFormJson(frm) {
  var o = {};
  var a = $(frm).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;
 }