我尝试准备一个请求。但是,它不起作用。我做错了什么?我已经为 JSON 提供了正确的 JSON 文件扩展名。不幸的是,它不起作用。
控制台显示以下错误:
training.html:218 XMLHttpRequest cannot load file:///C:/Users/lil/Desktop/data.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
"events": [
{ "location": "San Francisco, CA", "date": "May 1", "map": "http://javascriptbook.com/code/c08/img/map-ca.png"},
{ "location": "Austin, TX", "date": "May 15", "map": "http://javascriptbook.com/code/c08/img/map-ny.png"},
{ "location": "New York", "date": "May 31", "map": "http://javascriptbook.com/code/c08/img/map-tx.png"}
]
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if(xhr.status === 200){
responseObject = JSON.parse(xhr.responseText);
var newContent = '';
for (var i = 0; i < responseObject.events.length; i++) {
newContent += '<div class="event">';
newContent += '<img src="' + responseObject.events[i].map + '" ';
newContent += 'alt="' + responseObject.events[i].location + '" />';
newContent += '<p><b>' + responseObject.events[i].location + '</b><br>';
newContent += responseObject.events[i].date + '</p>';
newContent += '</div>';
}
document.getElementById('content').innerHTML = newContent;
}
};
xhr.open('GET', 'data.json', true);
xhr.send(null);
<body>
<header><h1>The Maker Bus</h1></header>
<h2>The bus stops here</h2>
<section id="content"></section>
</body>
最佳答案
要使用 JSON 数据,您需要在开发环境中运行本地 Web 服务器,以下是最著名的:
Windows:
万普 ( http://www.wampserver.com/en/ )
Xampp 推荐 ( https://www.apachefriends.org/pt_br/index.html )
MAC OS X:
MAMP ( https://www.mamp.info/en/ )
替代选项(也是我最喜欢的)运行你的 cli 并安装节点和 http-server
- brew 安装节点
- npm 安装 http-server
- 在 json 文件夹中运行“http-server”
- 在您喜欢的浏览器中打开 Localhost:8080(通常默认端口为 8080)
关于javascript - JSON 请求不起作用 : Cross origin request not supported on file://URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38908042/