【问题标题】:Simplify my Jquery xajax like function简化我的 Jquery xajax 类函数
【发布时间】:2009-10-23 19:12:19
【问题描述】:

基本上,我试图复制 xajax 用 Jquery 给我的东西之一 -> 能够定义我的响应修改服务器端的内容,而无需设置任何客户端。按原样完美运行,但每次我想调用不同的 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);

【问题讨论】:

    标签: php javascript jquery xajax


    【解决方案1】:

    这应该可行:

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

    【讨论】:

    • `if (this.action == 'eval') { eval(this.content); } 其他 { $(this.target)[this.action](this.content); }
    • 我尝试了你刚才提出的各种变化。我会让你知道它是否有效......
    • 是的。贾斯汀的版本有效,但由于他是评论,所以你得到了投票。谢谢。
    【解决方案2】:

    我不确定你在问什么?在风格上,我会这样写:

    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 操作?

    【讨论】:

      猜你喜欢
      • 2015-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-20
      • 1970-01-01
      • 2011-02-16
      • 2014-12-12
      • 1970-01-01
      相关资源
      最近更新 更多