简体   繁体   中英

how to parse data from json file using java script

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>

$.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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM