0

how to parse data from json file using java script?

how to parse data from json file using java script i Got only empty alert box in json file.how to retreive full content of json file data

<select onchange="calTest()" id="sle">
    <option>Peter</option>
    <option>Zara</option>
    <option>one</option>
</select>
<input type="text" id="txt">
<!-- http://jsfiddle.net/ifaour/S4YYk/1/ -->

<!-- http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js -->
<script src="jquery.js"></script>
<script>
    function calTest() {
        var aname = document.getElementById("sle").value;

        var json = "";

        $.getJSON("test/test.json", function(data) {
            json = data;

        });
        alert(json);
        $.each(json, function(i, v) {

            if (v.name == aname) {
                document.getElementById("txt").value = v.age;
                alert(v.age);
                return;
            }
        });

    }
</script>

NiziL
  • 5,068
  • 23
  • 33
user2012989
  • 1
  • 1
  • 1
  • 4
    Java is to javascript as ham is to hamster, I edited to remove the Java tag :) – NiziL Feb 11 '15 at 13:58
  • 2
    possible duplicate of [How to return the response from an Ajax call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) –  Feb 11 '15 at 13:59
  • possible duplicate of [Parse JSON in JavaScript?](http://stackoverflow.com/questions/4935632/parse-json-in-javascript) – lopisan Feb 11 '15 at 14:00

1 Answers1

2

$.getJSON is async that means it is called after the alert... so json is still empty.

Try

$.getJSON("test/test.json", function(data) {
      json = data;
      alert(json);
});
Cracker0dks
  • 2,422
  • 1
  • 24
  • 39