我正在尝试从 JSON 文件中获取随机单词及其参数。
JSON 文件:
{
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];
}
我能够获得随机单词,在本例中为 ranWord1
、ranWord2
、ranWord3
、ranWord4
,ranWord5
。但是,我无法获取参数。例如,我想将 “这是句子 4”
存储在局部变量中。任何帮助将不胜感激!
更新:
外部 word.js 文件:
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]);
}
});
}
我正在尝试从外部文件获取数组,但现在我得到 randomData[1] 的 undefined
并且我得到了包括 [
和 在内的任何内容]
对于单词
最佳答案
除了 @AndyKillen 解决的 ajax 问题之外,您的 JSON 无效。您可以使用http://jsonlint.com/检查。
这将是有效的 JSON。
{
"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"
}
}
此外,在您的情况下,您甚至不需要如此复杂的 json。一个简单的数组就足够了:
[
"This is a sentence 1",
"This is a sentence 2",
"This is a sentence 3",
"This is a sentence 4",
"This is a sentence 5"
]
(除非您需要一些额外的数据) 这也会简化你的 JavaScript 代码。你可以这样做:
$.ajax({
url: file,
type: 'get',
dataType: 'json',
async: false,
success: function(data) {
var randomSentence = data[Math.floor(Math.random()*data.length)];
}
});
<小时/>
如果您需要这个词,您也可以这样做:
var data = [
["word1", "This is a sentence 1"],
["word2", "This is a sentence 2"],
["word3", "This is a sentence 3"],
["word4", "This is a sentence 4"],
["word5", "This is a sentence 5"]
]
var randomData = data[Math.floor(Math.random() * data.length)];
alert("word: " + randomData[0] + ", sentence: " + randomData[1]);
关于jquery - 从 json 文件中获取随机单词及其参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29709458/