这个怎么样:
例子
HTML
<button id="btn">Send</button>
用法
$(document).ready(function(){
//dummy data
var requests = {
types: [
'POST',
'PUT'
],
urls: [
'/url1',
'/url2'
],
data: [{
name: 'name1'
},{
name: 'name2'
}]
};
var ajaxian = new Ajaxian(requests, [
function(){console.log('success')},
function(){console.log('success2')}
]);
$(ajaxian).bind('allrequestcomplete', function(){
console.log('request sequence finished');
});
$(ajaxian).bind('requesterror', function(){
console.log('request sequence failed');
});
$('#btn').bind('click', function(){
ajaxian.startRequests();
});
});
阿贾贤
//Depricated method for jQuery 1.8 used, success -> done, error -> fail
function Ajaxian(requests, successHandlers){
var self = this;
var me = $(this);
var _currentIndex = 0;
var _requests = null;
var _successHandlers = null;
var construct = function(requests, successHandlers){
_requests = requests;
_successHandlers = successHandlers;
requestHandler();
}
var getCurrentIndex = function(){
//return _currentIndex++ too slow?
var oldIndex = _currentIndex;
_currentIndex++;
return oldIndex;
}
var requestHandler = function(){
console.log('event listener binded');
console.log(me);
me.bind('requestcomplete', function(data){
//console.log(me);
//console.log('event triggered');
var index = getCurrentIndex();
//console.log('step 0');
if(_successHandlers[index - 1]){
console.log(data);
_successHandlers[index - 1](data);
}
console.log('step 1');
if(!_requests.urls[index]){
me.trigger('allrequestcomplete');
return;
}
prepareAndSendRequest(index);
});
me.bind('requestfailed', function(data){
me.trigger('requesterror', data);
})
}
var prepareAndSendRequest = function(index){
console.log('current index: ' + index);
var type = _requests.types[index];// ? _requests.types[index] : _requests.types[0];
var url = _requests.urls[index];// ? _requests.urls[index] : '';
var data = _requests.data[index];// ? _requests.data[index] : {};
//console.log(type);
//console.log(url);
//console.log(data);
doRequest(type, url, data);
}
var doRequest = function(type, url, data){
$.ajax({
type: type,
url: url,
data: data
}).success(function(data){
console.log(data);
me.trigger('requestcomplete', data);
//test
//me.trigger('requestfailed', data);
}).error(function(data){
console.log(data);
me.trigger('requestfailed');
//test
//me.trigger('requestcomplete', data);
});
}
this.startRequests = function(){
console.log('trigger');
prepareAndSendRequest(getCurrentIndex());
}
construct(requests, successHandlers);
}