Get Data from JSON file using jQuery Ajax

Leave a Comment
In this article, we have to learn how to get data from JSON file using jQuery Ajax.

First add HTML as shown below -
 <p>
        click the button given below to get jSON data :<br>
    </p>
    <input type="submit" id="submit" />
    <div id="message">
    </div>

In this demo we have info.json file as shown below -
 [
{"Name" : "Kisan", "City" : "Ladol"},
{"Name" : "Devang", "City" : "Vijapur"},
{"Name" : "Sanket", "City" : "Ahmedabad"}

Now add below jQuery code to get above JSON data.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $('#submit').click(function () {
            $.ajax({
                type: "GET",
                url: "info.json",
                dataType: "json",
                success: function (data) {
                    var Name = "<ul>";
                    $.each(data, function (i, n) {
                        Name += "<li>" + n["Name"] + "</li>";
                    });
                    Name += "</ul>";
                    $('#message').append(Name);
                }
            });
            return false;
        });
    });
</script>

Demo
Get Data from JSON file using jQuery Ajax

0 comments:

Post a Comment