<script>
$(document).ready(function() {
$("#getMessage").on("click", function(){
// Only change code below this line.
$.getJSON("https://www.freecodecamp.org/json/cats.json", function(json) {
$(".message").html(JSON.stringify(json));
});
// Only change code above this line.
});
});
</script>
<style>
.message{height: 400px;}
</style>
<body>
<div class="message">
The message will go here
</div>
<button id="getMessage">Button</button>
My code is not rendering on jsfiddle, even though it works on this exercise:
Because unless authorized by the site containing the API (in this case freecodecamp.org), a different site (i.e. jsfiddle.net) can not use the API.
If you look at the console (Ctrl+Shft+I on Chrome), you will see the following error message:
XMLHttpRequest cannot load https://www.freecodecamp.org/json/cats.json.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'https://fiddle.jshell.net' is therefore not allowed access.
2 Likes
Ok so I made a local .json file, called weather.json and calling it locally, but it is still not outputting any data! Am I doing something wrong? My code is below… and I attached a screenshot with stuff thats in my json file…
JSON FILE CONTENTS: (attaching screenshot)
HTML CODE:
<!DOCTYPE html>
<html><title> get JSON data from API </title>
<script>
$(document).ready(function() {
$("#getMessage").on("click", function(){
// Only change code below this line.
$.getJSON("weather.json", function(json) {
$(".message").html(JSON.stringify(json));
});
// Only change code above this line.
});
});
</script>
<style>
.message{height: 400px;}
</style>
<body>
<div class="message">
The message will go here
</div>
<button id="getMessage">Button</button>
</body>
</html>
Unless you’re running it on a local server, you’re trying to get a file://
rather than an http://
resource, seciurity restrictions mean that won’t work