每当您通过 ajax 请求加载内容时,您必须确保所需的 js 设置/文件与您的内容一起加载。
在大多数情况下,在内容加载期间通过 drupal_add_js() 填充的 $javascript 静态变量不会发送到浏览器,但您可以手动执行此操作:
// 获取视图内容。
$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 。$视图;
出口;
$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>'
希望这可以帮助!