mercredi 5 février 2020

Merge arrays using jquery

I am calling Web API https://jsonmock.hackerrank.com/api/movies/search/?Title=spiderman. It returns The query response from the website is a JSON response with the following five fields: page, per_page, total, total_pages and data.

Data is An array of JSON objects containing movie information where the Title field denotes the title of the movie.

Note that this field is paginated so, in order to incorporate pagination, you must query https://jsonmock.hackerrank.com/api/movies/search/?Title=substr&page=pageNumber, where pageNumber is an integer denoting the page you would like to view (e.g., 1, 2, etc.).

I'm trying to Combine all the movies into an array. The below code is not working. Can you please help?

<script>
    $(document).ready(function () {
        $(function () {
            $("#getPeople").click(function (e) {
                console.log('calling function');
                $.ajax({
                    contentType: 'application/json',
                    type: "GET",
                    url: "https://jsonmock.hackerrank.com/api/movies/search/?Title=spiderman",
                    success: function (data, textStatus, jqXHR) {
                        console.log(data);

                        var totalPages = data.total_pages;
                        console.log(totalPages);


                        var listmovies = data.data;

                        console.log(listmovies.toString());

                        for (var i = 2; i <= totalPages; i++) {
                            console.log('calling loop');
                            $.ajax({
                                contentType: 'application/json',
                                type: "GET",
                                url: "https://jsonmock.hackerrank.com/api/movies/search/?Title=spiderman&page=" + i,
                                success: function (data, textStatus, jqXHR) {
                                     listmovies = [...listmovies, ...data.data];
                                },
                                error: function (jqXHR, textStatus, errorThrown) {
                                    $("#getPeopleResult").val(jqXHR.statusText);
                                }
                            });
                        }

                        console.log(listmovies.length);

                        for (var j = 0; j < listmovies.length; j++) {
                            console.log(listmovies[j].Title);
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        $("#getPeopleResult").val(jqXHR.statusText);
                    }
                });
            });
        });
    });
</script>


  [1]: https://jsonmock.hackerrank.com/api/movies/search/?Title=spiderman



Aucun commentaire:

Enregistrer un commentaire