0

I am new to JSON. I have data.json, jQuery.min.js and try.html files within a folder. The problem is that it doesn't show any output on the screen. I also tried some of the examples from other websites as well as StackOverflow too, but the problem remains the same. Please help me out.

try.html :

<body>
<div id="append-here"></div>
<script type="text/javascript" src="jquery-2.1.4.min.js"></script>
<script>
    $(document).on('ready', function(){
       $.getJSON('data.json', function (data) { 
          $.each(data, function(index, element) {
             $('#append-here').append(element.name);
        });
    });
});
</script>

data.json :

[ 
  { "id" : "1", "name" : "test1" },
  { "id" : "2", "name" : "test2" },
  { "id" : "3", "name" : "test3" },
  { "id" : "4", "name" : "test4" },
  { "id" : "5", "name" : "test5" } 

]

And this is what I get on JS console:

XMLHttpRequest cannot load file:///C:/Users/avi/Desktop/html/jsAjax/data.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
Avishekh Bharati
  • 1,858
  • 4
  • 27
  • 44
  • 2
    Mention the proper path of your file. Looks like you're accessing the file which is not on your server. – Nishant Ghodke Jul 17 '15 at 15:22
  • 1
    the error isn't thrown on the JSON file, you just can't access the file without the permissions from the browser you're using (chrome I think)... this is what `Cross origin request` means. – cramopy Jul 17 '15 at 15:23
  • It looks like you open html file in browser and try to make ajax request. You need to set up virtual host – Gleb Jul 17 '15 at 15:25
  • Try fully-pathing the `data.json` in your `$.getJSON()`, that might fix the CORS error. – Dave Jul 17 '15 at 15:25
  • You cannot use AJAX to get something that's on your local filesystem. – alan0xd7 Jul 17 '15 at 15:30
  • Actually, I just did it in simple Html and javaScript without localhost. Do I have to run it in local host ? – Avishekh Bharati Jul 17 '15 at 15:43
  • Firefox allows you to make ajax request on the file system, but you should really set up a dev server. – Musa Jul 17 '15 at 15:59
  • Thank you guys ... I wasted whole day, figuring out what's wrong until I asked here and finally found out that I need to run it in a localhost. – Avishekh Bharati Jul 17 '15 at 16:03

1 Answers1

0

Looks like you are running into a CORS problem: http://enable-cors.org/

See this for more info: A CORS POST request works from plain javascript, but why not with jQuery?

Community
  • 1
  • 1
Kerry Hatcher
  • 601
  • 6
  • 17