从Web API请求JSON数据

时间:2019-05-06 03:08:19

标签: jquery html ajax

我有一个JS方法,请求https://swapi.co/documentation#films中的数据以通过HTML页面返回电影列表。

我想编写一个JS方法,以从电影数据中获得'episode_id'属性返回单个电影(getSingleFilm)的数据。

我当前拥有的代码是

(function(){

    var dataChangedEvent = new Event('dataChanged')

    function SW() {
        this.url = 'https://swapi.co/api/films/'
        this.films = []
    }


    /* get data from the API endpoint and store it locally */
    SW.prototype.getData = function() {

        var self = this

        $.get({
           url: self.url,
           success: function(data) {
                /* store data as a property of this object */
                self.films = data
                /* trigger the data changed event */
                window.dispatchEvent(dataChangedEvent)
           }
        })
    }


    /* return the list of films */
    SW.prototype.getFilms = function() {
        if (this.films === []) {
            return []
        } else {
            return this.films.results
        }
    }


    /*--
    NEW METHOD HERE!
    Return a single film based off of the episode_id
    --*/
    SW.prototype.getSingleFilm = function(episodeID) {
        if (this.films === []) {
            return []
        } else {
            this.films.results.episode_id = episodeID
            /*--I'm having trouble continuing here--*/
        }
    }


    /* export to the global window object */
    window.app = window.app || {}
    window.app.SW = SW

})()

我正在通过另一个JS文件返回它

(function(){


    $(document).ready(function() {

        /* make a model instance and trigger data load */

        window.app.model = new window.app.SW()
        window.app.model.getData()

        /* set up handler for dataChanged event from model */

        $(window).on("dataChanged", function() {
            var films = window.app.model.getFilms()
            var film = window.app.model.getSingleFilm(4)

             for(var i=0; i<films.length; i++) {
                $("#movies").append("<li>Episode " + films[i].episode_id + " : " + films[i].title + " (" + films[i].director + ")" + " - " + films[i].release_date+ "</li>")
             }

             /*--Trying to return a new list with a single film here--*/
             $("#single_film").append("<li>Episode " + film.episode_id + "</li>")

        })
    })

})()

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Star Wars!</title>
  <link rel="stylesheet" href="styles/index.css">
</head>

<body>

  <ul id="movies"></ul>

  <ul id="single_film"></ul>

  <!-- Scripts -->

    <!-- load javascript libraries -->
  <script src="static/js/jquery-3.3.1.min.js"></script>
  <script src="static/js/model.js"></script>
  <script src="static/js/index.js"></script>
</body>

</html>

我不确定如何继续这种方法,但我一直被阻止。

感谢您的帮助

0 个答案:

没有答案