【題記】重復提交很蛋疼,每次的解決辦法是,在前端提交按鈕上做功夫,我baidu 也google了,姿勢換了N次,貌似找不到適合自己的項目的方法,好吧,寫一個。
【正文】:先上代碼:

/*
*
* jQuery Ajax 防止重復提交
* @author : suntiger035
* @data : 2012-5-31 17:13
*/
( function($){
var $ajax = $.ajax;
$ajax._reuqestsCache = {};
// 設置全局 AJAX 默認選項。
$.ajaxSetup({
mode: "block",
index: 0,
cache: false,
beforeSend: function(xhr, s) {
if (s.mode) {
if (s.mode === "abort" && s.index) {
if ($ajax._reuqestsCache[s.index]) {
$ajax._reuqestsCache[s.index].abort();
}
}
$ajax._reuqestsCache[s.index] = xhr;
}
}
});
// 這里我是重寫了getJSON方法,當然了,這名字隨便你改,別覆蓋jQuery本身的就可以了
$.extend({
getJSON: function(url, data, callback, options) {
options = $.extend({}, arguments[arguments.length - 1] || {});
if (options.mode === "block" && options.index) {
if ($ajax._reuqestsCache[options.index]) {
return false;
}
$ajax._reuqestsCache[options.index] = true;
}
if (options.crossDomain) {
options.dataType = "jsonp";
}
var type = "json";
if ($.isFunction(data)) {
callback = data;
data = null;
}
options = $.extend({
type: "GET",
url: url,
data: data,
success: callback,
dataType: "json"
}, options);
return $.ajax(options);
}
});
$(document).ajaxComplete( function(a,b,c){
if (c.index) $ajax._reuqestsCache[c.index] = null;
})
})(jQuery);
* jQuery Ajax 防止重復提交
* @author : suntiger035
* @data : 2012-5-31 17:13
*/
( function($){
var $ajax = $.ajax;
$ajax._reuqestsCache = {};
// 設置全局 AJAX 默認選項。
$.ajaxSetup({
mode: "block",
index: 0,
cache: false,
beforeSend: function(xhr, s) {
if (s.mode) {
if (s.mode === "abort" && s.index) {
if ($ajax._reuqestsCache[s.index]) {
$ajax._reuqestsCache[s.index].abort();
}
}
$ajax._reuqestsCache[s.index] = xhr;
}
}
});
// 這里我是重寫了getJSON方法,當然了,這名字隨便你改,別覆蓋jQuery本身的就可以了
$.extend({
getJSON: function(url, data, callback, options) {
options = $.extend({}, arguments[arguments.length - 1] || {});
if (options.mode === "block" && options.index) {
if ($ajax._reuqestsCache[options.index]) {
return false;
}
$ajax._reuqestsCache[options.index] = true;
}
if (options.crossDomain) {
options.dataType = "jsonp";
}
var type = "json";
if ($.isFunction(data)) {
callback = data;
data = null;
}
options = $.extend({
type: "GET",
url: url,
data: data,
success: callback,
dataType: "json"
}, options);
return $.ajax(options);
}
});
$(document).ajaxComplete( function(a,b,c){
if (c.index) $ajax._reuqestsCache[c.index] = null;
})
})(jQuery);