0

This code works inside HTML simulators, but does not work when I copy and paste it and try to run it in browser.

Why would that be? Is my browser putting up some sort of safeguard? How would I have to modify the code to make it work in-browser?

source:https://www.quackit.com/json/tutorial/json_with_http_jquery.cfm

Code replicated here:

<!doctype html>
<title>Example</title>

<!-- Load JQuery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js">
</script>

<!-- Load JSON file and output it-->
<script>
 $(function() {

  // User clicks the "getData" button
  $("#getData").click(function() {

// Put artistList element and JSON file location into a variable
var artistList = $("#artistList");
var url = "https://www.quackit.com/json/tutorial/artists.txt";

    // Get the JSON file
    $.getJSON(url, function(data) {

      // Put artist info into a variable
      var artists = data.artists.map(function(item) {
        return item.artistname + " (" + item.born + ")";
       });

      // Remove all child nodes (including text nodes) 
      artistList.empty();

       // Format artists with HTML tags 
      if (artists.length) {
        var content = "<li>" + artists.join("</li><li>") + "</li>";
        var list = $("<ul>").html(content);
         artistList.append(list);
       }
    });
  });
});
  </script>

<!-- The output appears here -->
<button id="getData">Display Artists</button>
<div id="artistList"></div>
amita00
  • 159
  • 1
  • 4
  • 13

1 Answers1

0

You have two problems when you try to run this html locally using the file protocol:

First, you have to change the src of the script adding http: in the beginning.

Second, the request to the external api in your code will be a cross-domain request, and it's default blocked by the browsers. Know more about it in Why does my JavaScript get a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error when Postman does not?