首页 > 解决方案 > 如何在 JQUERY 中加载带有 Lunr 数据的 JSON 文件?

问题描述

我根据此处的说明制作了一个带有 Lunr 搜索数据的 JSON 文件。所以它是一个 JSON 文件,其结构类似于{"documents":[{"body":"....

我可以设法在控制台中很好地运行这些命令:

var response = $.getJSON('/includes/js/lunr-index.json');
var docs = response.responseJSON.documents;

然而,当我的脚本中有同样的东西时,就像这样:

$( document ).ready(function() {
    var response = $.getJSON('/includes/js/lunr-index.json');
    var docs = response.responseJSON.documents;

    var idx = lunr(function () {
        this.ref('title');
        this.field('body');

        docs.forEach(function (doc) {
            this.add(doc);
        }, this);
    });
});

我明白了Cannot read property 'documents' of undefined

.getJSONJQuery的方法有什么遗漏吗?我不是 Javascript 程序员,所以提前抱歉。

这是我在控制台中运行它时的样子:

>>> var response = $.getJSON('/includes/js/lunr-index.json');

>>> response

{readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}

>>> var docs = response.responseJSON.documents;

docs
(53) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

所以 JSON 有效。只是这在脚本中不起作用。

编辑:

好的,所以这看起来像一个异步问题。我一直在尝试像这样重写它:

fetch('/includes/js/lunr-index.json')
    .then(response => response.json())
    .then(json => lunr(function () {
        this.ref('title');
        this.field('body');

        json.documents.forEach(function (doc) {
            this.add(doc);
        }, this);
    }));

但我不认为我知道这个承诺的东西是如何工作的。

标签: javascriptjquerylunrjs

解决方案


推荐阅读