Pregunta

Básicamente intentaba replicar una de las cosas que xajax me dio con Jquery - > La capacidad de definir lo que mi respuesta modifica del lado del servidor sin configurar nada del lado del cliente. Funciona perfectamente como está, pero cada vez que quiero llamar a una función Jquery diferente, tengo que agregarla a mis sentencias if.

Cada elemento de la matriz de respuesta contiene algo que debe cambiarse del lado del cliente.

Debería poder eliminar casi todo el this.action == 'blah' if enunciados y reemplazarlo con algún javascript inteligente, pero al parecer no soy lo suficientemente inteligente. :)

$ .showMessage es simplemente mi reemplazo de alerta, con un tiempo de espera y un bit fijo.

Función Jquery de mi cliente:

$.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;
};

Código del lado de mi servidor:

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);
¿Fue útil?

Solución

Esto debería funcionar:

$(this.target)[this.action](this.content);

Otros consejos

No estoy exactamente seguro de lo que estás preguntando? Estilísticamente, lo escribiría así:

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);
});

Si solo desea ejecutar lo que sea que el servidor le envíe, ¿no siempre se enviará una acción de evaluación?

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top