我试着准备一个请求。但是,它不起作用。我做错了什么?我已经为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);
&#13;
<body>
<header><h1>The Maker Bus</h1></header>
<h2>The bus stops here</h2>
<section id="content"></section>
</body>
&#13;
答案 0 :(得分:1)
要使用JSON中的数据,您需要在开发环境中运行本地Web服务器,这是最着名的:
<强>窗:强>
Wampp(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