Javascript JSON external file

0

I would like to upload an external json file to my html page via javascript.

When I tried, the following error occurred: "Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https".

One solution I found was to put all my code and run it for example by wampserver using localhost: 80, but I would not want it to have to install wamp or anything like that.

Is it possible to load the data from the json file without having to use this solution?

    
asked by anonymous 28.06.2017 / 20:52

2 answers

0

You need to use HTTP protocol, there is no other way, but to not install Wamp, you may have Node installed on your machine and install the link package. this will provide you an HTTP protocol without using Wamp Remember that http-server will do something similar to wamp.

    
28.06.2017 / 21:04
0

Cross origin requests is the key term here.

With this file://c: there, you're trying to load something from your user's filesystem. If that worked, your page could actively access the files on the disk of anyone who came into your page.

That would be more or less equivalent to having everyone's cell phone password entered their physical store.

Put JSON in the same folder as your WEB application and load as you would any CSS or Javascript. So the browser knows that you want to access something that is yours and not the user's.

Example of how to load a JSON like this. Have a Javascript file named foo.js :

var meuJson = JSON.stringify({pessoa: { idade: 30, nome: "fulano" }});
function obterJson() { return meuJson; }

And to consume on your page:

<script type="text/javascript">
    var json = obterJson();
</script>

Now, if you want to access it as if it were a JSON return from a service (ie using ajax ), there's no way around it. You will need an HTTP server to serve this same JSON.

    
28.06.2017 / 21:07