我正在尝试显示一个“警报”框,其中包含 JSON 文件中的文本。但我似乎无法从 JSON 文件中获取数据。它只是不会抛出警报框。
var thebook = JSON.parse(book);
function showAlert() {
alert(thebook[0].word);
}
<head>
<script type="text/javascript" src="book.json"></script>
</head>
<body>
<button onclick="showAlert()">show alert</button>
</body>
以及一个示例 JSON 文件
[
{
"word" : "cuiller",
"page" : 23
},
{
"word" : "arbre ",
"page" : 245
}
]
最佳答案
在您的 book.json
中,将 JSON 存储在变量中(如下面给出的 var book
)。
var book = [
{
"word" : "cuiller",
"page" : 23
},
{
"word" : "arbre ",
"page" : 245
}
];
在解析/警告它之前对其进行字符串化。
thebook = JSON.parse(JSON.stringify(book));
function showAlert() {
alert(thebook[0].word);
}
工作 JSFiddle 链接: https://jsfiddle.net/h5knqobs/9/
希望这有帮助!
关于javascript - 无法从外部本地json获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51301218/