Checkout MyThemeBox.com for Ionic & Flutter Themes

Parse JSON using Cordova (PhoneGap)

read-json-phonegap-cordova

Let's learn about how to parse JSON data using phonegap (cordova). We're going to** read json data using jquery** so we can use getJSON or Ajax method. To get sample json data, i'm gonna read JSON data from https://reqres.in

!! Important !!: Please download jquery and use it local to improve performance https://code.jquery.com/jquery-3.3.1.min.js

create new project

cordova create cordovajson
cd cordovajson

index.html  Let's write a code

    <!DOCTYPE html>
    <html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
        <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
        <script>
            $(document).ready(function() {

                $("#makeGetJSONRequest").click(function() {
                    console.log("makeGetJSONRequest");
                    $.getJSON("https://reqres.in/api/users?page=2", function(result) {
                        console.log(result.data);
                        $.each(result.data, function(i, field) {
                            $("#users").append("- " + field.first_name + " " + field.last_name + "<br/>");
                        });
                    });
                });

                $("#makeAjaxRequest").click(function() {
                    $.ajax({
                        type: "GET",
                        url: "https://reqres.in/api/users?page=2",
                        crossDomain: true,
                        cache: false,
                        success: function(result) {
                            $.each(result.data, function(i, field) {
                                $("#users").append("- " + field.first_name + " " + field.last_name + "<br/>");
                            });
                        }
                    });
                })

                $("#clear").click(function() {
                    $("#users").empty();
                });

            });
        </script>
    </head>

    <body>
        <button id="makeGetJSONRequest">using GetJSON</button>
        <button id="makeAjaxRequest">using Ajax()</button>
        <button id="clear">Clear Data</button>
        <div id="users"></div>
    </body>

    </html>