php - 简化我的 Jquery xajax 之类的功能

标签 php javascript jquery xajax

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

最佳答案

这应该有效:

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

关于php - 简化我的 Jquery xajax 之类的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1615365/

相关文章:

javascript - 根据顺序更改深层嵌套 Javascript 对象中同名属性的多个值

javascript - 我的 AJAX 只触发一次,

javascript - 使用输入数字值作为另一个字段的输入数字最大值

javascript - jquery-使用 elementFromPoint 通过 id 更改元素背景颜色

javascript - 将类添加到所有匹配的父 div

While 语句中的 If else 语句中的 PHP 多个变量

php - INSERT INTO 2表查询

php - 哪种方法对于大写文本 : CSS or PHP? 更有效

javascript - 改善慢 Angular 方向

php - 如何对表示具有多个答案的民意调查的两个表使用一个查询?