Hen*_*y H 6 ajax jquery drupal-8
我在一个页面上有两个并排的块。右侧是一个带有空 div 的自定义块,class="js-view-dom-id-ccd-update"。左侧是一个视图,其中将标题列为内容类型(“中心”)的链接。当用户单击其中一个链接时,我希望该记录的详细信息显示在右侧的块中。
我创建了一个视图(“center”),它将单个中心作为页面返回(机器名称 page_1”)。可以从 URL /center/## 访问该页面,其中 ## 是中心的节点 ID。我使用一个模板,使其仅显示中心内容,而不显示普通页面的其余部分。
我创建了一个 .js 文件,理论上,该文件将附加一个 AJAX 操作来调用该页面视图并将结果放入右侧的块中。这是基于我在这里找到的简短教程:https://www.thirdandgrove.com/rendering-view-ajax-drupal-8
(function ($) {
Drupal.behaviors.ajaxContentCenter = {
attach: function (context, settings) {
$('#content-center-list-block-2 li').once('attach-links').each(this.attachLink) ;
),
attachLink: function (idx, list) {
// determine the node ID from the link (not ideal but should work for now)
var link = $(list).find('a');
var href = $(link).attr('href');
var matches = /node\/(\d*)/.exec(href);
var nid = matches[1];
var view_info = {
// the view to get one center's record
view_name: 'center',
// the display ID for that view
view_display_id: 'page_1',
// the nid to pass to the view (but doesn't seem to work)
view_args: nid,
// the block to update has a class of js-view-dom-id-ccd-update
view_dom_id: 'ccd-update'
};
// ajax action details
var ajax_settings = {
submit: view_info,
// I'd have thought supplying the nid above would work but
// it doesn't, so I've included it here
url: '/center/'+nid,
element: list,
event: 'click'
};
Drupal.ajax(ajax_settings) ;
}
};
})(jQuery);
Run Code Online (Sandbox Code Playgroud)
当我单击链接时,我会看到一个小旋转器,表明 ajax 正在工作,并且在浏览器控制台中我可以看到 ajax 结果被发送回浏览器。不幸的是,它永远不会被放入右侧块中的 div 中。我看不到任何错误消息。
我尝试将右侧块的视图设为块而不是页面,但据我所知,没有可以调用的 URL 来访问它。
我是否误解了 Drupal.ajax 的工作原理?非常感激任何的帮助。
——亨利
解决了:
我知道我错过了什么。ajax_setting 数组需要“wrapper”和“method”元素(它们在文档中列为可选元素,但显然是我正在做的事情所必需的)。我发现它们描述的文档位于:https://api.drupal.org/api/drupal/core%21core.api.php/group/ajax/8.2.x#sub_form。我需要使用 id="ccd-update" 更新目标块中的 div 以匹配包装器。
var ajax_settings = {
submit: view_info,
url: '/center/'+nid,
element: list,
wrapper: 'ccd-update',
method: 'html',
event: 'click',
} ;
Run Code Online (Sandbox Code Playgroud)
仅使用包装器,链接在第一次单击时有效,但随后的单击无法更新块。将方法设置为 html 后,它就起作用了。
我不确定需要什么(如果有的话)view_info 数组。这留给读者作为练习。
-- 呵呵