Load A Json File In Local System Using Jquery/javascript
I am new to scripting languages. I have a new.json file and I want to load in gary.html HTML file. I do not want to run gary.html file on server. I want to run it locally on my mac
Solution 1:
As you've seen - you can't make AJAX requests to the local filesystem as it's a huge security issue. The only workaround for this is for the user to manually enable settings in their browser (which is not a great idea anyway). If you do not want this then you will have to use a central server for all requests.
The alternative is to avoid using AJAX by including the new.json
file in the page using an extra <script />
tag. You will also need to assign the object to a variable in the file, something like this:
// new.jsonvar newJson = {"a": [{"name":"avc"}, {"name":"Anna"}, {"name":"Peter"}]}
Then in gary.html
:
<head><scriptsrc="jquery.js"></script><scriptsrc="new.json"></script><script>
$(function() {
newJson.a.forEach(function(item) {
console.log(item.name);
});
})
</script></head>
Solution 2:
You can't make AJAX requests to the local filesystem as it's a huge security issue. Why cant you directly include the JSON data in HTML file directly. You wont have to make AJAX call to fetch the JSON.
<head><script>var jsonData = '{"a": [{"name":"avc"}, {"name":"Anna"}, {"name":"Peter"}]}';
for(var i=0; i< jsonData.a.length;i++)
{
var item = jsonData.a[i];
console.log(item.name);
}
</script></head>
Post a Comment for "Load A Json File In Local System Using Jquery/javascript"