我正在尝试共享使用 GitHub 页面完成的网站,但在加载 JSON 文件时遇到问题。
这是一个 friend 游戏服务器网站,使用 HTML 5、JavaScript 和 JSON,我尝试从本地主机运行它,它工作得非常好。
这个问题实际上是一个SyntaxError : Unexpected token < in JSON at position 0
当我尝试在 chrome 调试器中查找 JSON 文件时,我看不到 JSON 文件来检查问题可能来自何处。
JSON 文件:
{
"header_menu_games": "Games",
"header_menu_home": "Home",
"header_menu_rules": "Rules",
"header_menu_support": "Support",
"header_serverip_text": "Server ip:",
"header_serverip_copy_btn": "Copy"
}
我用来翻译的 JavaScript 代码:
if (isLanguageAvailable) {
var myRequest = new Request(`../../src/lang/${userLang}.json`);
console.info(`User language (${userLang}) is available`);
} else {
var myRequest = new Request("../../src/lang/en.json");
console.info(`The user language (${userLang}) is unfortunately not available`);
}
console.log(myRequest);
fetch(myRequest)
.then(resp => {
resp.json()
.then(data => {
document.getElementById("lang-header_serverip_text").innerHTML = data.header_serverip_text;
})
.catch(err => {
console.error(err);
});
})
.catch(err => {
console.error(err);
});
控制台错误:
JavaSript 捕获错误:
完整代码可用on GitHub .
最佳答案
我相信您收到 404 错误,因为您将链接指向存储库位置而不是实际内容。您链接到一个不存在的链接:https://vianpyro.github.io/src/lang/en.json
您可以通过以下两种方式之一执行此操作:
链接到存储库中文件的原始版本
指向您 friend 域中的正确位置
1。链接到原始版本
在 github 中,单击 Raw
,它应该会打开一个包含实际 JSON 的页面。
您会看到内容的实际链接是:https://raw.githubusercontent.com/Vianpyro/Aycraft/master/src/lang/en.json
<小时/>2。链接到托管位置
您最初的问题的一部分是您没有指向正确的路径。您 friend 的网站托管在 https://vianpyro.github.io/Aycraft而不是https://vianpyro.github.io/ .
这意味着该网站的基本网址是 https://vianpyro.github.io/Aycraft道路上的一切都必须遵循这一点。您必须在域名后面包含 /Aycraft
,因为这是网站的基本 URL。
关于javascript - 如何修复 'Unexpected token < in JSON at position 0'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57479949/