# 如何在使用 ajax 获取数据后刷新特定小部件

**URL:** <https://meta.discourse.org/t/how-to-refresh-a-particular-widget-after-getting-data-from-ajax/189616>\
**Category:** Development\
**Created:** [2021年五月7日 10:57 UTC](https://meta.discourse.org/t/how-to-refresh-a-particular-widget-after-getting-data-from-ajax/189616 "2021-05-07T10:57:47Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![sachin\_kumar](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/sachin_kumar/32/212559_2.png) [@sachin\_kumar](https://meta.discourse.org/u/sachin_kumar)\
**Post date:** [2021年五月7日 10:57 UTC](https://meta.discourse.org/t/how-to-refresh-a-particular-widget-after-getting-data-from-ajax/189616/1 "2021-05-07T10:57:47Z")

</div>

你好，我一直在尝试为我的 Discourse 网站实现自定义导航栏，以下是我的代码：

```javascript
$.ajax("/categories.json").then(
  (data) => {
    data.category_list.categories.map((val) => {
      api.addNavigationBarItem({
        name: val.name,
        displayName: val.name,
        title: val.name,
        href: `/c/${val.slug}`,
        forceActive: (category, args, router) => {
          return router.currentURL === `/c/${val.slug}`;
        }
      });
    });
  }
);

```

现在我必须手动跳转到其他链接，新添加的导航项才会显示出来。在通过 AJAX 获取数据后，该如何重新加载导航栏？

谢谢！

---

<div class="post-metadata">

**Author:** ![Johani](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/johani/32/176920_2.png) [@Johani](https://meta.discourse.org/u/Johani)\
**Post date:** [2021年五月7日 21:08 UTC](https://meta.discourse.org/t/how-to-refresh-a-particular-widget-after-getting-data-from-ajax/189616/2 "2021-05-07T21:08:45Z")

</div>

这里的问题在于，你添加新导航项的代码仅在 AJAX 请求完成后才会执行。因此，在请求完成的短短几毫秒内，默认（未修改的）导航栏会被显示出来。这就是为什么你在初次加载页面时会看到它。

一旦你跳转到其他页面，请求就已经完成，你的更改就会开始生效。

回答你的问题：是的，你可以条件性地重新渲染组件。

不过，这并非你真正想要的解决方案。你甚至不需要 AJAX 请求。你可以直接从应用中获取分类列表。这样既能解决你的问题，又能节省一次额外的 HTTP 请求。试试下面的代码（基于你的代码修改）：

```javascript
// 查找分类
const categoryList = api.container.lookup("site:main").categories;

// 为每个分类添加一个导航项
categoryList.map(val => {
  api.addNavigationBarItem({
    name: val.name,
    displayName: val.name,
    title: val.name,
    href: `/c/${val.slug}`,
    forceActive: (category, args, router) => {
      return router.currentURL === `/c/${val.slug}`;
    }
  });
});

```

---

<div class="post-metadata">

**Author:** ![sachin\_kumar](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/sachin_kumar/32/212559_2.png) [@sachin\_kumar](https://meta.discourse.org/u/sachin_kumar)\
**Post date:** [2021年五月8日 11:59 UTC](https://meta.discourse.org/t/how-to-refresh-a-particular-widget-after-getting-data-from-ajax/189616/3 "2021-05-08T11:59:22Z")

</div>

谢谢 Joe，现在运行得非常顺利。
