2011-10-06 33 views
2

當我送與jQuery Ajax請求,我指定data陣列,像可以jQuery的阿賈克斯被告知只有形式ID

data: {param1: 'somevalue', param2: 'another value' } 

,我看到寫在MooTools的1.2一些舊代碼,它似乎MooTools的能夠按原樣發送整個表單,而無需逐個指定字段。你只需要給它一個表格ID,在這個例子中就是theform

var theNewRequest = new Request.HTML({url:'ajaxpage.php'}).post($('theform')); 

jQuery中是否有類似的東西?

回答

3

是的,您可以使用序列化函數來發送窗體的序列化內容。

$.post("ajaxpage.php", $("#theform").serialize()); 
2

$.post('somewhere',$('formid').serialize(), function(data){})怎麼樣?

+0

冷靜,我會嘗試一下 – sameold

0

jQuery .serialize()方法以標準URL編碼表示法創建文本字符串。它在代表一組表單元素的jQuery對象上運行。

http://api.jquery.com/serialize/

2

我寫這個劇本一兩個星期回簡化AJAX表單提交:

/** 
* 
* Autesion King of Thebes 
* 
* Also, a simple script by zzzzBov to automatically submit a form via AJAX 
*/ 
(function($){ 
"use strict"; 
function autesion(options){ 
    var settings; 
    settings = $.extend(true, {}, autesion.defaultSettings, options); 
    this.submit(function(e){ 
    var $this, ajaxSettings, $form; 

    if (!e.isDefaultPrevented()) 
    { 
     $this = $(this); 
     $form = $(e.target); 
     ajaxSettings = $.extend({}, settings.ajaxSettings, { 
     'data':$form.serialize(), 
     'type':$form.attr('method') || 'GET', 
     'url':$form.attr('action') 
     }); 

     if (settings.useEvents) 
     { 
     ajaxSettings.beforeSend=function(j,s){ 
      $this.trigger(new $.Event('autesion.beforeSend', {jqXHR:j, settings:s})); 
     }; 
     ajaxSettings.complete=function(j,t){ 
      $this.trigger(new $.Event('autesion.complete', {jqXHR:j, textStatus:t})); 
     }; 
     ajaxSettings.error=function(j,t,e){ 
      $this.trigger(new $.Event('autesion.error', {jqXHR:j, textStatus:t, errorThrown:e})); 
     }; 
     ajaxSettings.success=function(d,t,j){ 
      $this.trigger(new $.Event('autesion.success', {jqXHR:j, textStatus:t, ajaxData:d})); 
     }; 
     } 

     e.preventDefault(); 
     $.ajax(ajaxSettings); 
    } 
    }); 

    if (settings.useEvents) 
    { 
    this.bind('autesion.beforeSend', settings.beforeSend) 
     .bind('autesion.complete', settings.complete) 
     .bind('autesion.error', settings.error) 
     .bind('autesion.success', settings.success); 
    } 

    return this; 
}; 
autesion.defaultSettings={ 
    'ajaxSettings':{}, 
    'beforeSend':$.noop, 
    'complete':$.noop, 
    'error':$.noop, 
    'success':$.noop, 
    'useEvents':true 
}; 

$.fn.autesion = autesion; 

}(jQuery)); 

我敢肯定它可以顯著改善,但它應該工作的,是隻要你不需要文件輸入支持。

要使用它,只需撥打:

$('form').autesion(); 

簡單形式爲:

$form = $('form'); 
$form.ajax({ 
    'data': $form.serialize(), 
    'type': $form.attr('method') || 'GET', 
    'url': $form.attr('action') 
});