2014-04-02 53 views
0

我在我的Javascript代码中解析了一个json文件,如下所示。交叉来源请求只支持HTTP,即使在Chrome后也不固定 - 允许文件从文件访问

$.getJSON('file:///dashboard.json', function (json) { 

然而,它抛出

XMLHttpRequest无法加载file:///dashboard.jsonCross origin requests仅支持HTTP

我一直在寻找的解决方案几乎7小时统称,但大多数人建议使用此:

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --allow-file-access-from-files 

open -b com.google.chrome --args --allow-file-access-from-files 

,甚至当我第二个命令打开Chrome浏览器,则会引发相同的交叉原点请求错误。

第一个命令甚至没有运行,如下所示。

$ /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome 
[708:1287:0401/174956:ERROR:process_singleton_mac.cc(103)] Unable to obtain profile lock. 
$ [0401/174957:ERROR:mach_broker_mac.mm(152)] Failed to look up named parent port: 0x44e unknown error code 

我试图启动与该文件服务器,端口8000,并通过提供网址访问http://localhost:8000/dashboard.json它,但它并没有解决跨起源请求错误。 (我的网络应用程序运行在端口8080)。

什么问题?我怎样才能解决这个问题? 请帮帮我。谢谢。

+1

您正在寻找交叉来源。看到这个答案:http://stackoverflow.com/questions/3102819/disable-same-origin-policy-in-chrome/6083677#6083677 –

回答

1

不同的端口号也会导致交叉来源问题:http:// localhost:8000访问来自http:// localhost:8080的json文件。解决跨源资源访问问题有多种方式,例如CORS,Server-proxy和JSONP。

我想你可以尝试在你的情况下使用JSONP来解决这个问题。

步骤1:更新dashboard.json并将文件类型更改为javascript。 (如果你想知道JSONP是如何工作的,请参阅本doc

//assume that the json data looks like this {tabs:[{id:"1",name:"tab1",status:"on"},{id:"2",name:"tab2",status:"off"}]} 
var data = {tabs:[{id:"1",name:"tab1",status:"on"},{id:"2",name:"tab2",status:"off"}]};   
onGetDashboardJSON(data); 

第2步:使用$就在JSONP的方式来获取交叉起源JSON数据

$.ajax({ 
    url: "http://localhost:8080/dashboard.js", 
    dataType:"jsonp", 
    success: function(response){ 

    }, 
    error: function(response){ 

    } 
}); 

function onGetDashboardJSON(result){ 
    //do anything you want with the JSON 
    console.log(result); 
} 

希望这会有所帮助。

+0

在我看来,通过使用AJAX调用与file://协议加载数据不是很好的解决方案。它有浏览器(Chrome不允许使用文件协议进行AJAX调用,但IE支持它(ActiveXObject))和安全问题。 @ user2418202曾尝试将json文件放入Web服务器并使用http://协议访问它,因此我建议了一个访问跨源资源的解决方案,并试图解释他的尝试不起作用的原因。 – Chickenrice

相关问题