0

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

0

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Access it like this

json[0].name

because [] brackets are array operators.

Comments

1

Try this:

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

5 Comments

Also, your JSON is malformed it should start with curly braces {[{name:"",blah}]}
jsonlint.com says it's valid. Why do you think it is invalid? edit: No, the top level "element" has either to be an array or object. {[{name:"",blah}]} on the other side is totally incorrect.
It might work just fine for javascript, but in other languages it won't work. Just trying to keep to best practices!
thanks , but the issue was that i am not working on webserver enivornment
It should, because it is valid according to the specification.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.