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>

3
  • 4
    Java is to javascript as ham is to hamster, I edited to remove the Java tag :) Commented Feb 11, 2015 at 13:58
  • 2
    possible duplicate of How to return the response from an Ajax call? Commented Feb 11, 2015 at 13:59
  • possible duplicate of Parse JSON in JavaScript? Commented Feb 11, 2015 at 14:00

1 Answer 1

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);
});
Sign up to request clarification or add additional context in comments.

Comments

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.