Semplifica la mia funzione simile a Jquery xajax
-
06-07-2019 - |
Domanda
Fondamentalmente stavo cercando di replicare una delle cose che xajax mi ha dato con Jquery - > La possibilità di definire ciò che la mia risposta modifica lato server senza impostare nulla sul lato client. Funziona perfettamente così com'è, ma ogni volta che voglio chiamare una funzione Jquery diversa, devo aggiungerla alle mie istruzioni if.
Ogni elemento nella matrice di risposta contiene qualcosa da modificare sul lato client.
Dovrei essere in grado di eliminare quasi tutte le istruzioni this.action == 'blah' e sostituirle con qualche javascript intelligente, ma a quanto pare non sono abbastanza intelligente. :)
$ .showMessage è semplicemente il mio sostituto dell'avviso, con un timeout e un po 'appiccicoso.
Funzione Jquery del mio client:
$.doAjax = function(func,values) {
$.ajax({ data: values, url: '/time/ajax/' + func, type: 'POST', dataType: 'json', timeout: 5000,
error: function(xhr, ajaxOptions,thrownError){ $.showMessage('Error processing request: ' + func,10000);$('#debug').html(xhr.responseText); },
success: function(data){
if(data){
$.each(data, function(){
if ( this.action == 'attr' ) $(this.target).attr(this.content);
if ( this.action == 'removeAttr' ) $(this.target).removeAttr(this.content);
if ( this.action == 'addClass' ) $(this.target).addClass(this.content);
if ( this.action == 'removeClass' ) $(this.target).removeClass(this.content);
if ( this.action == 'html' ) $(this.target).html(this.content);
if ( this.action == 'text' ) $(this.target).text(this.content);
if ( this.action == 'val' ) $(this.target).val(this.content);
if ( this.action == 'eval' ) {
try {
eval(this.content);
}
catch(err) {
$.showMessage(err,5000);
};
};
});
}
}
});
return this;
};
Il mio codice lato server:
header("Content-type: text/plain");
$response = array();
$response[] = array('action'=>'html','target'=>'#booked_time_group_unbilled','content'=>get_booked_time_group_unbilled());
$response[] = array('action'=>'html','target'=>'#booked_time_my_unbilled','content'=>get_booked_time_my_unbilled());
$response[] = array('action'=>'eval','target'=>'','content'=>"$.showMessage('The selected time has been deleted',5000,true)");
echo json_encode($response);
Soluzione
Questo dovrebbe funzionare:
$(this.target)[this.action](this.content);
Altri suggerimenti
Non sono esattamente sicuro di cosa stai chiedendo? Stilisticamente, lo scriverei così:
var handlers = {
attr: function() { $(this.target).attr(this.content) },
removeAttr: function() { $(this.target).removeAttr(this.content) },
// etc.
};
$.each(data,function() {
handlers[this.action].call(this);
});
Se vuoi solo eseguire qualunque cosa il server rispedisca, cosa che non sempre rispedisce un'azione di valutazione?