多ajax请求的各类解决方案(同步, 队列, cancel请求)

2019-09-14 07:15:39王冬梅

$(document).dequeue(options.className);
} else {
ajaxRequest[options.className] = false;
}
}
});
$(document).queue(options.className, function () {
$.ajax(options);
});
if ($(document).queue(options.className).length == 1 && !ajaxRequest[options.className]) {
ajaxRequest[options.className] = true;
$(document).dequeue(options.className);
}
};
$.ajaxSingle = function (settings) {
var options = $.extend({ className: 'DEFEARTNAME' }, $.ajaxSettings, settings);
if (jqXhr[options.className]) {
jqXhr[options.className].abort();
}
jqXhr[options.className] = $.ajax(options);
};
})(jQuery);
var ajaxSleep = (function () {
var _settings = {
type: 'GET',
cache: false,
success: function (msg) {
var thtml = $('#txtContainer').html();
$('#txtContainer').html(thtml + "<br />" + msg);
}
};
return {
get: function (seconds, mode, isAsync) {
var mode = mode || 'ajax',
isAsync = isAsync || false;
$[mode]($.extend(_settings, {
url: "ResponsePage.aspx?second=" + seconds,
async: isAsync,
className: 'GET'
}));
},
post: function (seconds, mode, isAsync) {
var mode = mode || 'ajax',
isAsync = isAsync || false;
$[mode]($.extend(_settings, {
type: 'POST',
url: "PostPage.aspx",
data: { second: seconds },
async: isAsync,
className: 'POST'
}));
}
};
} ());
var launch = function (settings) {
$('#txtContainer').html('');
var mode = settings.mode,
isAsync = settings.isAsync;
ajaxSleep.get(12, mode, isAsync);
ajaxSleep.get(10, mode, isAsync);
ajaxSleep.get(8, mode, isAsync);
ajaxSleep.post(6, mode, isAsync);
ajaxSleep.post(4, mode, isAsync);
ajaxSleep.post(2, mode, isAsync);
}
$(document).ready(function () {
//第1种case
$('#btnLaunchAsync').click(function () {
launch({ isAsync: true });
});
//第2种case
$('#btnLaunchSync').click(function () {
launch({});
});
//第2种case
$('#btnLaunchQueue').click(function () {
launch({ mode: 'ajaxQueue', isAsync: true });
});
//第3种case
$('#btnLaunchSingle').click(function () {
launch({ mode: 'ajaxSingle', isAsync: true });
});
});

default.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/default.js"></script>
</head>
<body>
<form id="form1" runat="server">
<input type="button" id="btnLaunchAsync" value="Launch Asynchronous Request" />
<input type="button" id="btnLaunchSync" value="Launch Synchronous Request" />
<input type="button" id="btnLaunchQueue" value="Launch Requested Queue" />