简体   繁体   中英

trouble using JSON data from Datamuse API in p5.js

So I want to build a very simple web app where the user enters some text and a paragraph is then created from the same text. Each word in the paragraph is inside a span tag so when the user hovers over it, synonyms of that word are displayed on the console.

I'm pretty sure the part of the code that causes the problem is this :

var lookupLink;
var data;
function preload(){
    lookupLink = 'https://api.datamuse.com/words?ml=';
}
function changeWord(){
    data = loadJSON(lookupLink+this.html())
    var index = floor(random((Object.keys(data).length)));
    console.log(data[index].word);
    //the above console.log gives an error.
}

here's the full code just in case : https://pastebin.com/ViNZ1jse

Instead of logging the word , it shows :

Uncaught TypeError: Cannot read property 'word' of undefined
    at p5.Element.changeWord (sketch.js:39)

I'm guessing this is because the data object hasn't finished loading yet when I try to log one of it's properties , but I don't know how I can work around this. EDIT : Oh and I forgot to mention There's also another issue where I can load the data from https://api.datamuse.com/words?ml= link but not https://api.datamuse.com/words?rel_syn= link.

https://p5js.org/reference/#/p5/loadJSON

loadJson can receive a callback that will be executed when your json is loaded. So I assume this will working :

loadJSON(lookupLink+this.html(), function(data) {
  var index = floor(random((Object.keys(data).length)));
  console.log(data[index].word);
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM