Json file dosen't show up in google chrome

2019-09-08 15:16发布

问题:

I'm developing a page that shows a Json file via jQuery and Leaflet.

The Flickr side is working fine, but when I try to $.getJSON o, I see an error in Chrome's console:

XMLHttpRequest cannot load file:///C:/AppServ/www/PFEleaflet/test%20geojson/lot.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

But when i try to open the .html page in FireFox, the Json file shows up, it work fine.

This is the code I am using:

var geoLayer = L.geoJson().addTo(map);
var geoList = L.control.geoJsonList(geoLayer);

geoList.on('item-active', function(e) {
    $('#selection').text(JSON.stringify(e.layer.feature.properties));
})
.addTo(map);

$('#geofile').on('change', function(e) {

    $.getJSON(this.value, function(json) {

        map.removeLayer(geoLayer);

        geoLayer = L.geoJson(json).addTo(map);
        map.fitBounds( geoLayer.getBounds() );

        geoList.reload( geoLayer );
    });
}).trigger('change');

Any help please.

回答1:

Suggest opening this page on a local server instead of using file protocol which will cause problems here and other places. Nodejs serve is great, or Ruby's builtin http server.

Here is a great list. https://gist.github.com/willurd/5720255



回答2:

By default, Chrome doesn't allow any page to access the file:/// scheme, even if the page is in that scheme as well (on your local machine). You can override this default by adding a parameter to the Google Chrome shortcut like so:

Go to your desktop and make a copy of the Google Chrome shortcut. Right click on the shortcut and click Properties. In the properties window, add the following to the target attribute (outside of the quotes):

--allow-file-access-from-files

This should result in a target attribute that looks something like this:

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files

Now close any open Google Chrome windows and make sure no chrome.exe processes are running. Drag your file over the new shortcut that you just created, and your page should launch and work correctly.

Note: I don't recommend changing the original shortcut or making this the default because when this is enabled, any page can access the file:/// scheme, not just pages on your machine.