Looking to build a work-around of the following.
$.getJSON(\'myfile.json\', function (data) {
showAll(data);
});
I want to avoid using a we
AJAX is about making asynchronous HTTP requests. You need a web server to make those requests and receive those responses. JQuery's .get()
method won't let you avoid a web server.
The only way I can think of would be to include an iframe in your code and set the source of the iframe to your resource that includes the JSON. Then, you could use JSON.parse()
on the contents of the iframe.
If you have a permission correctly, you can get the file using <script>
tag.
in html:
<script src="./favs.js"></script>
<script src="./script.js"></script>
in favs.js
:
var favs = [
{ url: 'http://google.com' },
{ url: 'http://stackoverflow.com' }
];
in script.js
:
console.log(favs); // you can use favs as global variables
Otherwise, if you want to use ajax call such as $.getJSON()
, you should have a webserver somehow.
Additionally, you can load js file dynamically. May you can use the code below for example:
function loadScript(path, onload) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = path;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(script, s);
if(onload) s.onload = onload;
}
Simple, fast, but bad for real project solution:
myfile.json
to data.js
(name doesn't matter).var myData = {...your json...}
<script src="./data.js"></script>
to your html file.myData
variable from javascript with all data.This solution is bad because you add a new variable in global scope and browser would still make a http request to get this .js file.
Also, If you want to make ajax requests to your local files, you can use http server. Take a look at very simple node js http-server.
This would be a 3 step process.
Move the JSON file into a folder with you other web pages
In the JSON file, give the obejct a name i.e. var data = {...};
In the file that you wan to use it just call it with the <script src='myJSON.js'></script>
If it is static JSON resource, why make another network request. Network is expensive. You can change to .js and include the file in the page.