jQuery Ajax 防止重复提交
2012-05-31 17:48 sniper007 阅读(7271) 评论(22) 编辑 收藏 举报【题记】重复提交很蛋疼,每次的解决办法是,在前端提交按钮上做功夫,我baidu 也google了,姿势换了N次,貌似找不到适合自己的项目的方法,好吧,写一个。
【正文】:先上代码:
View Code
/**
* 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);