Mi piacerebbe sapere se esiste un approccio migliore alla creazione di oggetti ajax riutilizzabili per jquery.Pattern JS ajax riutilizzabile (jquery)
Questo è il mio codice non testato.
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>
si potrebbe prendere in considerazione di tornare in sé la promessa della tua sender.ajax ('ritorno $ .ajax ({...}) ') in modo che sia possibile allegare altre callback dal client. Naturalmente se preferisci nascondere completamente l'ajax di jquery all'altro codice, non dovresti farlo. – Stefan