我正在尝试使用localhost将外部脚本加载到网站,但是我总是收到错误消息: “未捕获的SyntaxError:JSON中位置1处的意外令牌o 在JSON.parse() 在HTMLScriptElement.songScript.onload”
var songScript = document.createElement('script');
songScript.type = "text/javascript";
songScript.src = "http://localhost:5500/songs.jsons";
songScript.id = "songs";
songScript.onerror = (error) => {
console.log("Unable to load songs code.");
}
songScript.onload = () => {
songList = JSON.parse(songScript);
}
document.getElementsByTagName('head')[0].appendChild(songScript);
这是我的JSON文件:
{
"chords3": "d3 d1, d2 f3 a3, d1 a2, d2 f3 a3, d3 d1, d2 f3 a3, d1 a2, d2 f3 a3, d3 d1, d2 f3 a3, d1 a2, d2 f3 a3, d3 d1, d2 e3 g3, d1 cs3, d2 cs3 e3 g3",
"demo": "notes here"
}
答案 0 :(得分:0)
结束这个问题。我使用fetch函数而不是附加代码:
fetch("http://localhost:5500/songs.json")
.then((res)=>res.json())
.then((data)=>{
songs = data;
}).catch(()=>{
console.log("Unable to load songs.json.");
});