I am new to scripting languages. I have googled for loading and parsing the JSON file using jQuery. I have taken the help of those links that I got from Stack Overflow.
I have this JSON file named new.json .
{ "a": [
{"name":"avc"},
{"name":"Anna"},
{"name":"Peter"},
{"Folder": "ABC", "name":[
{"name":"John"},
{"name":"Anna"},
{"Folder":"XYZ", "name":[
{"name":"fdgh"},
{"name":"hdfghh"},
{"Folder":"JKL", "name":[
{"name":"gdfgdfgggggg"},
{"name":"hddddddddddddddddddddddddddddh"},
{"Folder":"PQR", "name":[
{"name":"gddddddg"},
{"name":"ddhh"}
]
}
]
}
]
}
]
}
]
}
And this is my code jQuery/JavaScript code to load the new.json file. I have written my Code inside the <script> tag.
<script src="jquery-3.1.0.js"></script>
<script type="text/javascript" language="javascript" src="C:\Users\Girish\Desktop\new.json"></script>
<script type="text/javascript">
var out="<ul>";
var j=0;
function functionName(event) {
$('li[id^="foo"]').click(function(e){
e.stopPropagation();
var x = $(this).last().find(' > ul').clone().find('ul').remove().end();
$('#list').html(x);
$("#list .hide").show();
});
}
$(document).ready(function() {
$('li[id^="foo"]').each(function() {
$(this).on('click', {param: this.id}, functionName);
});
});
function read(obj){
for(var i = 0; i < obj.length; i++)
{
if(obj[i].Folder)
{
var name = "foo"+ ++j;
var name2 = "<li id=" + name + ">";
out = out+ name2 + obj[i].Folder + "<ul>";
document.getElementById("tree").innerHTML = out;
read(obj[i].name);
out=out+"</ul></li></ul>";
}
else
{
var name2 = "<li class=\"hide\">";
out = out+ name2 + obj[i].name;
document.getElementById("tree").innerHTML = out;
out=out+"</li>";
}
}
}
function show()
{
//read(a)
var myItems;
$.getJSON('new.json', function(data) {
myItems = data.a;
read(myItems)
});
}
</script>
and this is <body> tag.
</div>
<div id="list"></div>
When I am running this code on Google Chrome. It is giving this error
jquery-3.1.0.js:9392 XMLHttpRequest cannot load file:///C:/Users/Girish/Desktop/new.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource. on console. I have googled this error, I have found some links that says that run the same file on Mozilla Firefox.
The same code I am running on Mozilla Firefox, It is not giving any error. It is showing Items in #tree div. but when I am clicking on any item in tree div. It is not showing its child elements in #list div.
Now I want to load the json file on both Chrome and Firefox. How can I fix the above error?
Why child items are not showing in list div when clicking on any item in tree div?
Thanks