Javascript 当使用file:///协议时,js如何动态加载json文件
我想根据url查询参数中的名称在本地测试动态加载json文件的js(Javascript 当使用file:///协议时,js如何动态加载json文件,javascript,jquery,json,url,Javascript,Jquery,Json,Url,我想根据url查询参数中的名称在本地测试动态加载json文件的js(file://protocol) 我用的是铬 file:///Users/eladb/Downloads/map/map_tmp.html?jsonPath=routes_2.json 我试过这个: var jsonPath = getParameterByName('jsonPath'); $.getJSON(jsonPath, function(json) { console.log(json); // this
file://
protocol)
我用的是铬
file:///Users/eladb/Downloads/map/map_tmp.html?jsonPath=routes_2.json
我试过这个:
var jsonPath = getParameterByName('jsonPath');
$.getJSON(jsonPath, function(json) {
console.log(json); // this will show the info it in firebug console
});
得到了这个错误:
jquery.min.js:4 XMLHttpRequest cannot load file:///Users/eladb/Downloads/map/routes_2.json?_=1454238808580. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
是否有一种快速的方法来创建一个只用于测试的本地服务器(mac、java) 很简单:你不能在生产中使用。这是一种在客户端机器上无法规避的安全特性 不过,您可以在计算机的浏览器设置中禁用它。在Chrome中,以命令行参数“禁用web安全”启动浏览器。Firefox可以通过
about:config->security.fileuri.strict\u origin\u policy->false禁用该功能
以下是在MacOS上启动web服务器的指南:您应该设置一个轻量级web服务器。它们有很多,但由于您熟悉Javascript,我建议使用Node创建一个满足您需求的节点
下面的脚本将允许您在本地指定端口,并将url参数映射到文件位置(尽管您可以轻松修改以处理更多)
安装节点:
将此脚本保存到一个目录(我称之为simple server.js)
在该目录中打开终端窗口并运行以下命令:
节点simple-server.js
simple-server.js代码
//https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/
var myPort = 8080;//Set pot to one not used on your box
var fs = require('fs')
var http = require('http');
console.log('Starting server...')
var server = http.createServer(function(req, resp){
console.log('Request received. ');
//get url param and change file based on param or url
var param = req.url.split('?');
if (param.length > 1) {
param = param[1].split('=');
if (param.length > 1) {
param = param[1];
}
}
var fileLoc = '';//Map your param to files here
switch(param){
case 'bar':
fileLoc = 'C:/Projects/nodebin/bar.json';
break;
case 'baz':
fileLoc = 'C:/Projects/nodebin/baz.json';
break;
default:
fileLoc = 'C:/Projects/nodebin/foo.json';
break;
}
fs.readFile(fileLoc, 'utf8', function(err, data) {
if (err) {
consoole.log(err);
}
else {
console.log(data);
resp.statusCode = 200;
resp.setHeader('Content-Type', 'application/json');
resp.write(data);//Echo JSON
resp.end();
}
});
}).listen(myPort);
在运行chrome或安装apache时,您可以尝试添加--allow file access from files选项。file:///Users/eladb/Downloads/map/map_tmp.html?jsonPath=routes_2.json 是json吗path@VasimVanzara那么现在,如何修复绕过错误呢?最简单的解决方法是运行服务器,您可以使用此处列出的任何一个OneLiner:我运行了/Applications/Google\Chrome.app/Contents/MacOS/Google\Chrome--允许从文件访问,但再次出现相同错误是的,我运行了open-a Google\Chrome\Canary--args--允许文件访问
。我仍然得到jquery.min.js:4 XMLHttpRequest无法加载file:///Users/eladb/Downloads/map/routes_2.geojson. 跨源请求仅支持协议方案:http、数据、chrome、chrome扩展、https、chrome扩展资源。
我认为您还需要--禁用web安全性