Load JSON data to Table using Jquery

Load JSON data to table using Jquery

Demo

See the Pen bLjwzy by Vinothkumar Rajendran (@fedtutorial) on CodePen.0

Note
For demo purpose I am using external api from www.mocky.io

JSON


//service.json
{
    "Cities": ["LUSAKA", "HARARE"],
    "Countries": ["ZAMBIA", "ZIMBABWE"]
}

Script


<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title>WCF Client</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
    <table id="location" border='1'>
        <tr>
            <th>Countries</th>
            <th>Cities</th>
        </tr>
    </table>
    <script>
        var service = 'service.json';

        $(document).ready(function() {

            jQuery.support.cors = true;

            $.ajax({
                type: "GET",
                // url: service + '/service/',
                url: service,
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                cache: false,
                success: function(data) {

                    var trHTML = '';

                    $.each(data.Countries, function(i, item) {

                        trHTML += '<tr><td>' + data.Countries[i] + '</td><td>' + data.Cities[i] + '</td></tr>';
                    });

                    $('#location').append(trHTML);

                },

                error: function(msg) {

                    alert(msg.responseText);
                }
            });
        })
    </script>
</body>
</html>

Note

If you are working in local environment, please use some local server (XAMPP, WAMP, Apache) to run this code. Because of JSON local access it is not working directly without server.

You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *