0

基本的に、私はxajaxがJqueryで私に与えたものの1つを複製しようとしていました->クライアント側を何も設定せずに私の応答がサーバー側を変更するものを定義する機能。そのままで完全に機能しますが、別のJquery関数を呼び出すたびに、それをifステートメントに追加する必要があります。

応答配列の各要素には、クライアント側で変更されるものが含まれています。

this.action =='blah' ifステートメントのほとんどすべてを取り出して、賢いjavascriptに置き換えることができるはずですが、どうやら私は十分に賢くありません。:)

$ .showMessageは、タイムアウトとスティッキービットを備えた、アラートの単なる代替品です。

私のクライアントのJquery関数:

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

私のサーバー側コード:

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

2 に答える 2

2

これはうまくいくはずです:

$(this.target)[this.action](this.content);
于 2009-10-23T19:22:58.290 に答える
0

あなたが何を求めているのか正確にはわかりませんか?スタイル的には、次のように書きます。

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

サーバーが送り返すものを実行したい場合、常に eval アクションを送り返すだけではありませんか?

于 2009-10-23T19:25:29.690 に答える