繁体   English   中英

JSON请求不起作用:file:// URL不支持跨源请求

[英]JSON request not working: Cross origin request not supported on file:// URL

我试图准备一个请求。 但是,它不起作用。 我做错了什么? 我给了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服务器,这是最著名的:

视窗:

Wampp( http://www.wampserver.com/en/

Xampp推荐( https://www.apachefriends.org/pt_br/index.html

MAC OS X:

MAMP( https://www.mamp.info/zh/

替代选项(我也很喜欢)运行cli并安装节点和http-server

  1. brew安装节点
  2. npm安装http-server
  3. 在您的json文件夹中运行“ http-server”
  4. 在您喜欢的浏览器中打开Localhost:8080(通常默认端口为8080)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM