无需禁用Chrome跨域安全,实现本地HTML加载游戏JSON文件
解决本地文件加载的CORS问题(无需禁用浏览器安全设置)
你遇到的CORS错误是浏览器安全策略导致的:file://协议下不允许发起XMLHttpRequest请求,而你当前用$.getJSON读取文件路径的方式正好触发了这个限制。下面提供的方案既能在本地打开HTML文件时正常工作,也能适配Web服务器环境,完全不需要禁用浏览器安全设置。
核心解决思路
直接使用浏览器原生的File API读取用户通过<input type="file">选择的文件内容,不需要依赖XHR请求,彻底绕开file://协议的CORS限制。
修改后的代码
优化的HTML(可选,提升用户体验)
给文件选择框加上accept=".json"属性,只允许用户选择JSON文件:
<input type="file" name="gameData" id="gameData" accept=".json"> <button id="loadGame">Load Game</button>
替换后的JavaScript代码
$("#loadGame").on("click", function() { const fileInput = document.getElementById("gameData"); const selectedFile = fileInput.files[0]; // 检查用户是否选中了文件 if (!selectedFile) { consoleWrite("请先选择一个游戏数据JSON文件"); return; } // 使用FileReader读取文件内容 const reader = new FileReader(); reader.onload = function(e) { try { // 解析JSON内容 const gameData = JSON.parse(e.target.result); // 为游戏变量赋值(和你原来的逻辑一致) round1Chain = gameData.round1Chain; consoleWrite(`Round 1: ${round1Chain}`); round2Chain = gameData.round2Chain; consoleWrite(`Round 2: ${round2Chain}`); round3Chain = gameData.round3Chain; consoleWrite(`Round 3: ${round3Chain}`); round4Chain = gameData.round4Chain; consoleWrite(`Round 4: ${round4Chain}`); speedChain1 = gameData.speedChain1; consoleWrite(`Speed 1: ${speedChain1}`); speedChain2 = gameData.speedChain2; consoleWrite(`Speed 2: ${speedChain2}`); speedChain3 = gameData.speedChain3; consoleWrite(`Speed 3: ${speedChain3}`); bonusChainA = gameData.bonusChainA; consoleWrite(`Bonus A: ${bonusChainA}`); bonusChainB = gameData.bonusChainB; consoleWrite(`Bonus B: ${bonusChainB}`); bonusChainC = gameData.bonusChainC; consoleWrite(`Bonus C: ${bonusChainC}`); consoleWrite(`Game loaded.`); } catch (error) { consoleWrite("文件解析失败,请确认是有效的JSON格式"); console.error(error); } }; // 以文本格式读取文件 reader.readAsText(selectedFile); });
方案优势
- 本地运行:完全绕开
file://协议的CORS限制,不需要修改任何浏览器设置,用户直接打开本地HTML文件就能用。 - 服务器环境:同样兼容,File API是浏览器原生能力,和服务器部署方式无关,用户上传的文件在客户端直接解析,无需发送到服务器(如果不需要保存的话)。
- 用户友好:支持任意命名的JSON文件,用户只需通过文件选择框选中即可,比替换固定JS文件的方式便捷得多。
内容的提问来源于stack exchange,提问作者Anthony LoPrimo
相关产品推荐
相关产品推荐

