Bootstrap5 hover触发popover AJAX加载显示[object Object]问题求解
问题根因
显示[object Object]是因为$.getJSON是异步方法,你在content回调里直接return它的返回值,拿到的是jQuery的jqXHR请求对象,不是你在AJAX成功回调里拼接的表格字符串。Bootstrap Popover初始化时只会同步读取content函数的返回值作为内容,不会等待AJAX请求完成,因此把请求对象转成字符串后就显示成了[object Object]。
另外你原代码没开html: true配置,就算内容正常返回,HTML标签也会被转义成纯文本,没法渲染成表格。
修复代码
调整实现逻辑:初始化时先给默认加载提示,监听popover显示事件再异步拉取内容,请求完成后通过BS5的Popover实例方法更新内容即可:
// 初始化Popover $(".jtxndtl").popover({ delay: 500, html: true, // 开启HTML渲染,否则表格标签会被转义 content: '加载中...', trigger: 'hover' }); // 监听显示事件,异步加载内容 $(".jtxndtl").on('show.bs.popover', function () { const $elem = $(this); // 已加载过内容就跳过重复请求 if ($elem.data('popoverLoaded')) return; const reqUrl = $elem.data('link'); $.getJSON(reqUrl, function (res) { const respData = res.msg; let tableHtml = `<table class="border"> <tr> <th>Date</th> <th>Description</th> <th>Payee</th> <th>Outflow</th> <th>Inflow</th> </tr>`; $.each(respData, function (_, item) { tableHtml += `<tr> <td>${item.event_date}</td> <td>${item.description}</td> <td>${item.payee}</td> <td>${item.dr_amount}</td> <td>${item.cr_amount}</td> </tr>`; }); tableHtml += '</table>'; // 获取Popover实例更新内容 const popover = bootstrap.Popover.getInstance($elem[0]); popover.setContent({ '.popover-body': tableHtml }); // 标记加载完成 $elem.data('popoverLoaded', true); }); });
注意事项
- 必须配置
html: true,否则所有HTML标签都会被作为纯文本展示,无法渲染表格结构 - 增加了加载完成标记,避免每次鼠标悬浮触发popover都重复发起接口请求
- 直接使用Bootstrap 5原生实例API更新内容,兼容BS5版本,不存在版本适配问题
内容的提问来源于stack exchange,提问作者Ravi
相关产品推荐
相关产品推荐

