I am trying to get the random word and its parameter from the JSON file.
JSON file:
{
ranWord1 {
sentence: "This is a sentence 1"
},
ranWord2 {
sentence: "This is a sentence 2"
},
ranWord3 {
sentence: "This is a sentence 3"
},
ranWord4 {
sentence: "This is a sentence 4"
},
ranWord5 {
sentence: "This is a sentence 5"
}
}
JS:
function readFiles() {
var result = null;
var file = 'dictionary.json';
$.ajax({
url: file,
type: 'get',
dataType: 'json',
async: false,
success: function(data) {
result = data;
}
});
var lines = result.split(", ");
var randLineNum = Math.floor(Math.random() * lines.length);
return lines[randLineNum];
}
I am able to get the random word which in this case is ranWord1, ranWord2, ranWord3, ranWord4, ranWord5. But, I am not able to get the parameters. I would like to store, for example, "This is a sentence 4" in a local variable. Any help will be appreciated!
UPDATE:
External word.js file:
var data = [
["ranWord1", "This is a sentence 1"],
["ranWord2", "This is a sentence 2"],
["ranWord3", "This is a sentence 3"],
["ranWord4", "This is a sentence 4"],
["ranWord5", "This is a sentence 5"]
]
JS:
function readFiles() {
var result = null;
var file = 'word.js';
$.ajax({
url: file,
type: 'get',
data: 'data',
dataType: 'script',
async: false,
success: function(data) {
var randomData = data[Math.floor(Math.random() * data.length)];
result = randomData;
alert("word: " + randomData[0] + ", sentence: " + randomData[1]);
}
});
}
I am trying to get the array from an external file but now I am getting undefined for randomData[1] and I am getting anything including [ and ] for word
Aucun commentaire:
Enregistrer un commentaire