Bader H Al Rayyes
Bader H Al Rayyes

Reputation: 522

alert JSON element by using jquery

i am trying to alert a JSON element using JQuery , here is my code:

data.js JSON data

[
    {
  "name": "bader",
  "major": "medicine",
  "id": "334453"
    }
]

Jquery code

$(document).ready(function() {

      $.getJSON("data.js", function(json) {
   alert("JSON Data: " + json.name);
 });



});

i tried to inspect element i had this error on my consol

XMLHttpRequest cannot load file:///data.js. Origin null is not allowed by Access-Control-Allow-Origin.

i am still very new to handling JSON and JQUERY , i do not know where i went wrong here , if someone could help

Upvotes: 0

Views: 2493

Answers (3)

Jason Foglia
Jason Foglia

Reputation: 2531

Try this:

$.ajax({
  url: "data.js",
  dataType: 'json',
  contentType:"application/json",
  success: function(data)
  {
      alert(JSON.stringify(data, null, "\t"))
  }
});

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816462

file:///data.js indicates that you are loading the page directly from your local file system.

Browsers have restrictions for Ajax request, they don't allow access to remote domains (if the remote domain does not allow it) or local files (though this can be enabled afaik (somehow, depends on the browser)).

The easiest way, IMHO, is to access your file through a server, not from the file system.
If you have Python, you can simply start a local server in the current directory with python -m SimpleHTTPServer. That's enough for testing and better than local file system access.


Regarding the output: json will be an array, so you have to access the name of the first object with json[0].name.

Upvotes: 5

Jānis Gruzis
Jānis Gruzis

Reputation: 995

Access it like this

json[0].name

because [] brackets are array operators.

Upvotes: 1

Related Questions