我寫這個劇本一兩個星期回簡化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')
});
冷靜,我會嘗試一下 – sameold