重復(fù)提交很蛋疼,每次的解決辦法是,在前端提交按鈕上做功夫,我baidu 也google了,姿勢(shì)換了N次,貌似找不到適合自己的項(xiàng)目的方法,好吧,寫(xiě)一個(gè)。
【正文】:先上代碼:
View Code
/**
* jQuery Ajax 防止重復(fù)提交
* @author : suntiger035
* @data : 2012-5-31 17:13
*/
(function($){
var $ajax = $.ajax;
$ajax._reuqestsCache = {};
//設(shè)置全局 AJAX 默認(rèn)選項(xiàng)。
$.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;
}
}
});
//這里我是重寫(xiě)了getJSON方法,當(dāng)然了,這名字隨便你改,別覆蓋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);
增加的參數(shù)描述
jQuery ajax原本的參數(shù)不變,增加了,index,mode,crossdomain 三個(gè)參數(shù)(jQuery 1.5增加了crossdomain,這里保留為了向后兼容)
index : 每個(gè)請(qǐng)求的索引,默認(rèn)為0,任何值,
mode :請(qǐng)求模式,有兩個(gè)值,“abort”,“block”
abort : 將之前的請(qǐng)求abort掉,
block : 將之后的請(qǐng)求abort掉。
crossdomain : true時(shí)候,為jsonp請(qǐng)求,跨域
方法描述$.getJSON(),用法跟原本的getJSON方法一致,只不過(guò),我增加了一個(gè)參數(shù),參數(shù)設(shè)置,始終是最后一個(gè)參數(shù)
說(shuō)明如上。
測(cè)試代碼
<input type="button" id="btn" value="click me" />
<script type="text/javascript">
$("#btn").click(function(){
$.getJSON('handle/try-1.php', {aa:11},function(data){
console.log(data);
},{
mode : 'block',
index : "111111111"
});
$.getJSON('handle/try-1-1.php', {aa:11},function(data){
console.log(data);
});
});
</script>
demo---mode : "block"
$.getJSON('handle/try-1.php', {aa:11},function(data){
console.log(data);
},{
mode : 'block',
index : "111111111"
});
請(qǐng)求顯示:
demo---mode : "abort"
$.getJSON('handle/try-1.php', {aa:11},function(data){
console.log(data);
},{
mode : 'abort',
index : "111111111"
});
請(qǐng)求顯示: