How can I load a JSON file with Lunr data in JQUERY?

40 views Asked by At

I've made a JSON file with Lunr search data according to the instructions here. So it's a JSON file that's structured like {"documents":[{"body":"....

And I can manage to run these commands fine in the console:

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

Yet when I have the same thing in my script, like this:

$( 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);
    });
});

I get Cannot read property 'documents' of undefined.

Is there something missing about JQuery's .getJSON method? I'm not a Javascript programmer, so sorry in advance.

Here's what it looks like when I run it in the console:

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

>>> response

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

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

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

So the JSON works. It's just that this doesn't work in the script.

Edit:

Ok, so this looks like an async issue. I've been trying to rewrite it like this:

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);
    }));

But I don't think I know how this promise stuff works.

0

There are 0 answers