我想知道是否有更好的方法来为jQuery创建可重用的ajax对象。可重复使用的JS ajax模式(jQuery)
这是我未经测试的代码。
var sender = {
function ajax(url, type, dataType, callback) {
$.ajax({
url: url,
type: type,
dataType: dataType,
beforeSend: function() {
onStartAjax();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
callback.failure(XMLHttpRequest, textStatus, errorThrown);
},
success: function(data, textStatus) {
callback.success(data, textStatus);
},
complete: function (XMLHttpRequest, textStatus) {
onEndAjax();
}
});
},
function onStartAjax() {
// show loader
},
function onEndAjax() {
// hide loader
}
};
<script type="text/javascript">
var callback = {
success: function(data, textStatus) {
$('#content').html(data);
},
failure: function(XMLHttpRequest, textStatus, errorThrown) {
alert('Error making AJAX call: ' + XMLHttpRequest.statusText + ' (' + XMLHttpRequest.status + ')');
}
}
sender.ajax(url, type, dataType, callback);
</script>
你可能会考虑返回的承诺本身在sender.ajax('返回$阿贾克斯({...} )'),以便您可以附加来自客户端的其他回调。当然,如果你宁愿从其他代码中完全隐藏jQuery的ajax,你也不应该那样做。 – Stefan 2012-08-25 23:45:02