Pergunta

Basicamente, eu estava tentando replicar uma das coisas que Xajax me deu com o jQuery -> A capacidade de definir o que minha resposta modifica o lado do servidor sem configurar nada do lado do cliente. Funciona perfeitamente como está, mas cada vez que quero chamar uma função jQuery diferente, tenho que adicioná -la às minhas instruções if.

Cada elemento na matriz de resposta contém algo para ser alterado no lado do cliente.

Eu deveria ser capaz de tirar quase tudo isso. :)

$ .ShowMessage é simplesmente o meu substituto para alerta, com um tempo limite e um bit pegajoso.

Minha função jQuery do meu 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;
};

Meu código lateral do meu 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);
Foi útil?

Solução

Isso deve funcionar:

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

Outras dicas

Não sei exatamente o que você está perguntando? Estilisticamente, eu escrevia assim:

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 você deseja apenas executar o que o servidor enviar de volta, o que nem sempre envia de volta uma ação de avaliação?

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top