0

我目前正在通过自定义模块中的 ajax 请求加载我的视图:

$.getJSON('/reports/summarized-progress/get_output_activities/'+nid, null,activities);

上述请求的 drupal 页面返回以下内容:

$output_arg=arg(3);
$html="";
$activities=views_embed_view('activities','block_activities',$output_arg); //this returns a view accordion view
if(!empty($activities)) {
$html.='';
$html.=$activities;
$html.='';
}
drupal_json_output(array('data'=>$html));

手风琴/可折叠功能不适用于加载的内容。任何想法是否需要通过 module_load_include 在我的自定义模块中包含任何文件?为此需要做什么?

4

1 回答 1

1

每当您通过 ajax 请求加载内容时,您必须确保所需的 js 设置/文件与您的内容一起加载。

在大多数情况下,在内容加载期间通过 drupal_add_js() 填充的 $javascript 静态变量不会发送到浏览器,但您可以手动执行此操作:

  • 这是一个有效的 Drupal 6 示例:
  // 获取视图内容。
  $view = views_embed_view($name, $display_id);

  // 获取javascript数据。
  $js = drupal_add_js(NULL, NULL, 'header');

  // 准备要在客户端处理的数据。
  $settings = drupal_to_js(call_user_func_array('array_merge_recursive', $js['setting']));

  // 告诉客户端使用收集的 $settings 扩展 Drupal.settings。
  $script = '<script type="text/javascript">
               jQuery.extend(true, Drupal.settings, ' . $settings . ');
             </脚本>';

  drupal_set_header('Content-Type:text/html; charset=utf-8');
  打印 $script 。$视图;
  出口;
  • 在 Drupal 7 中相同:
  $view = views_embed_view($name, $display_id);

  $js = drupal_add_js(NULL, array('type' => 'setting'));
  $settings = drupal_json_encode(call_user_func_array('array_merge_recursive', $js['settings']['data']));

  $script = '<script type="text/javascript">
               jQuery.extend(true, Drupal.settings, ' . $settings . ');
             </脚本>';

  drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
  打印 $script 。$视图;
  出口;

注意: 如果您的手风琴视图依赖于特定的 .js 文件,请确保该文件来源于发生 ajax 请求的每个页面。通常,如果在没有视图的情况下加载了这样的页面(全页面加载),您必须显式地获取此文件。

您可以在 hook_page_preprocess() 实现中实现这一点:

function moduleName_preprocess_page(&$variables) {
  // Include .js to the page so views can rely on in future ajax request
  drupal_add_library('system', 'ui.accordion');
  drupal_add_js(drupal_get_path('module', 'views_accordion') . '/views-accordion.js');

  // Add the css for fixing/preventing accordion issues.
  drupal_add_css(drupal_get_path('module', 'views_accordion') . '/views-accordion.css');

  // ...
}

...或者通过在请求内容时包含文件(就像我们对 Drupal.settings 所做的那样),只需在 ajax 回调的 $script 变量中添加一个脚本标签:

$script .= '<script type="text/javascript" src="sourcefile.js"></script>'

希望这可以帮助!

于 2014-04-27T17:37:14.277 回答