[added:] Thank you guys for the reply. I understand that ajax has to used on a server. I wonder if there is a way to load the data from local json file into js in this example?
I have a file named employee.json. I tried load this JSON data into JavaScript. I saved both the .json and .html files on my desktop but when I click in the HTML, there is nothing shown. I tried to use alert() in the .ajax() method but it does not work. I am not sure what is wrong with my AJAX method. What do I need to do to take the id from the JSON and put it into an array in javaScript? Thank you in advance.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
var res = [];
$.ajax({
url: 'employee.json',
dataType: 'json',
method: 'get',
cache: false,
success: function(data) {
$(data.employee).each(function(index, value) {
res.push(value.id);
});
document.getElementById("demo").innerHTML = res.toString();
}
});
</script>
</body>
</html>
{
"employee": [{
"id" : 1,
"firstName" : "Lokesh"
},{
"id" : 2,
"firstName" : "bryant"
},{
"id" : 3,
"firstName" : "kobe"
}]
}
I saved both .json and .html file on my desktopYou cannot run AJAX requests on the local file system due to the security restrictions on modern browsers. If you check the console you'll probably see a lot of errors and warnings about this. You need to run on a web server.console.log()to debug, notalert(). Also, you can replacedocument.getElementById("demo").innerHTML = res.toString();with$('#demo').html(res)error: function(){alert('error')})and you'll see the alert