如何在Drupal进行ajax调用后重新加载自定义JavaScript文件?

时间:2010-07-28 20:15:31

标签: javascript ajax drupal

如何在Ajax调用完成后重新加载自定义JavaScript文件?

在我的情况下,我有一个自定义JavaScript文件来操纵视图数据和 过滤器。它在第一次加载页面时效果很好。

但是一旦用户设置过滤器并点击Apply,即在Ajax调用之后,JavaScript似乎停止工作。它在那里,但没有注册任何事件。

我在Drupal.org上阅读了一些文章,但这并没有给我一个可靠的解决方案。

注意 - 它不是模块.js文件,而是主题文件夹下的自定义独立.js文件。

3 个答案:

答案 0 :(得分:3)

您应该阅读JavaScript in Drupal,尤其是any part about Drupal.bahaviors

重点是您需要将自定义JavaScript文件转换为Drupal.behaviors,因为这些将重新附加到通过AJAX动态加载的内容,如调用。

答案 1 :(得分:1)

问题可能是 - “如何在重复的回调参数上更新js函数”

这就是我所做的:

我的表格是这样的:

$form['letterdrop_id'] = array(                       
    '#type' => 'select',                              
    '#title' => 'Letterdrops',                        
    '#options' => $letterdrops,                       
    '#prefix' => '<div id="replace_div_ld">',         
    '#suffix' => '</div>',                            
    '#ajax' => array(                                 
      'callback' => 'agc_ems_form_map_change',        
      ),                                              
    );                                                

使用此回调函数:

function agc_ems_form_map_change($form, &$fstate) {              
   return array(                                                 
    '#type' => 'ajax',                                           
    '#commands' => array(
      // this command is to reload a form element                                        
      ajax_command_replace("#agc_map", render($form['map'])),    
      // this command does the business and calls my custom function, 
      // with a parameter object supplied
      array('command' => 'afterAjaxCallbackExample',             
          'selectedValue' => 'i am not a fish',                  
    )                                                            
  ));                                                            
}                                                                

这是我的js函数

(function($, Drupal) {                                                      
  // put function into drupal commands:   
  Drupal.ajax.prototype.commands.afterAjaxCallbackExample = 
     function(ajax, response, status) {
    // response object as passed in our Ajax callback          
    // do what you want in here
    alert(response.selectedValue);                                          
  };                                                                        
}(jQuery, Drupal));      

100%归功于jaypan

答案 2 :(得分:-1)

要添加脚本,您需要使用document.createElement(“script”),您不能只设置innerHTML。有关处理单独浏览器的好例子,请参阅http://www.phpied.com/javascript-include-ready-onload/