使用JavaScript和HTML显示API结果

时间:2017-01-24 13:31:47

标签: javascript html giphy-api

首先,我很擅长使用API​​。而英语不是我的第一语言。我已经在网上搜索过了,但却找不到我正在寻找的内容,或者至少我对我所阅读的内容并不了解,以了解如何改变并将其应用于我的情况。

我正在使用Omdb API和Giphy API,制作一个愚蠢的页面。我正在使用JavaScript和HTML。

最后,我希望页面显示用户搜索电影+主题上的GIF的搜索结果。

我到目前为止,我得到了两个API的结果。这一切都很好,很好。我不知道怎么做的是从这些结果出现,例如,电影标题和.gif文件。我分裂返回结果的尝试到目前为止都失败了。有什么建议?以下是我的JavaScript代码。

var form = document.getElementById('search-form');

form.addEventListener("submit", search);

function search(event) {
  event.preventDefault();
  document.getElementById("present_result").innerHTML = "";
  if(this.elements.query.value === '') {
    alert("Enter search word!");
  } else {
    var rawInputData = this.elements.query.value;
    var fixedInputData = rawInputData.split(" ");
    var inputData = encodeQueryData(fixedInputData);
    var inputDataGif = encodeQueryDataGif(fixedInputData);

    function encodeQueryData(data) {
       let ret = [];
       for (let d in data)
         ret.push(encodeURIComponent(data[d]));
       return ret.join('%20');
    }

    function encodeQueryDataGif(data) {
       let ret = [];
       for (let d in data)
         ret.push(encodeURIComponent(data[d]));
       return ret.join('+');
    }

    var omdbAPI = new XMLHttpRequest();
    var gifAPI = new XMLHttpRequest();
    var omdbURL = "http://www.omdbapi.com/?s=" + inputData + "&type=movie";
    var gifURL = "http://api.giphy.com/v1/gifs/search?q=" + inputDataGif + "&limit=1&api_key=dc6zaTOxFJmzC";

    omdbAPI.addEventListener("load", function() {
      if (this.responseText === '{"Response":"False","Error":"Movie not found!"}')
      {
        alert("No result.");
      } else {
        var result = JSON.parse(this.responseText);
        console.log(result);
        result = JSON.stringify(result);
        document.getElementById("present_result").innerHTML = result;
      }
    });

      gifAPI.addEventListener("load", function() {
        if (this.responseText === '{"Response":"False","Error":"Not found!"}')
        {
          alert("No Result.");
        } else {
          var result = JSON.parse(this.responseText);

          console.log(result);
          result = JSON.stringify(result);
          document.getElementById("present_gif").innerHTML = result;
        }
      });

    omdbAPI.open("get", omdbURL, true);
    omdbAPI.send();
    gifAPI.open("get", gifURL, true);
    gifAPI.send();
  }
}

在HTML下面。

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Mashup test</title>
        <link rel="stylesheet" type="text/css" href="style.css">
    </head>
    <body>
      <!-- Form -->
      <form action="" method="get" id="search-form" class="search-form">
          Movie: <input type="text" name="query">
          <button type="submit" id="submit">Search</button>
      </form>

      <!-- Result -->
      <div id="present_result">
      </div>
      <div id="present_gif">
      </div>
      <script src="scripts.js"></script>
    </body>
</html>

以下是OMDb的示例结果:

{
    "Search": [{
        "Title": "Titanic",
        "Year": "1997",
        "imdbID": "tt0120338",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BZDNiMjE0NDgtZWRhNC00YTlhLTk2ZjItZTQzNTU2NjAzNWNkXkEyXkFqcGdeQXVyNjUwNzk3NDc@._V1_SX300.jpg"
    }, {
        "Title": "Titanic II",
        "Year": "2010",
        "imdbID": "tt1640571",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMTMxMjQ1MjA5Ml5BMl5BanBnXkFtZTcwNjIzNjg1Mw@@._V1_SX300.jpg"
    }, {
        "Title": "Titanic: The Legend Goes On...",
        "Year": "2000",
        "imdbID": "tt0330994",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMTg5MjcxODAwMV5BMl5BanBnXkFtZTcwMTk4OTMwMg@@._V1_SX300.jpg"
    }, {
        "Title": "Titanic",
        "Year": "1953",
        "imdbID": "tt0046435",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMTU3NTUyMTc3Nl5BMl5BanBnXkFtZTgwOTA2MDE3MTE@._V1_SX300.jpg"
    }, {
        "Title": "Raise the Titanic",
        "Year": "1980",
        "imdbID": "tt0081400",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMTY5MTQwNzMxNV5BMl5BanBnXkFtZTcwMzkwOTMyMQ@@._V1_SX300.jpg"
    }, {
        "Title": "The Legend of the Titanic",
        "Year": "1999",
        "imdbID": "tt1623780",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMjMxNDU5MTk1MV5BMl5BanBnXkFtZTgwMDk5NDUyMTE@._V1_SX300.jpg"
    }, {
        "Title": "The Chambermaid on the Titanic",
        "Year": "1997",
        "imdbID": "tt0129923",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMWUzYjgyNDEtNTAyMi00M2JjLTlhMzMtMDJmOGM1ZmYzNzY4XkEyXkFqcGdeQXVyMTA0MjU0Ng@@._V1_SX300.jpg"
    }, {
        "Title": "In Search of the Titanic",
        "Year": "2004",
        "imdbID": "tt1719665",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMTAzNjY0NDA2NzdeQTJeQWpwZ15BbWU4MDIwMzc1MzEx._V1_SX300.jpg"
    }, {
        "Title": "Titanic",
        "Year": "1943",
        "imdbID": "tt0036443",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMTU2Njg4MDgxN15BMl5BanBnXkFtZTcwNzE4MjYyMQ@@._V1_SX300.jpg"
    }, {
        "Title": "S.O.S. Titanic",
        "Year": "1979",
        "imdbID": "tt0079836",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMTMwOTU5MDU0OV5BMl5BanBnXkFtZTcwMDc4OTYyMQ@@._V1_SX300.jpg"
    }],
    "totalResults": "170",
    "Response": "True"
}

来自Giphy的样本结果:

{
    "data": [{
        "type": "gif",
        "id": "pWDH6fkHgGHza",
        "slug": "titanic-leonardo-dicaprio-pWDH6fkHgGHza",
        "url": "http://giphy.com/gifs/titanic-leonardo-dicaprio-pWDH6fkHgGHza",
        "bitly_gif_url": "http://gph.is/Z15kA0",
        "bitly_url": "http://gph.is/Z15kA0",
        "embed_url": "http://giphy.com/embed/pWDH6fkHgGHza",
        "username": "",
        "source": "http://tomhiddles.tumblr.com/post/37231367662",
        "rating": "g",
        "content_url": "",
        "source_tld": "tomhiddles.tumblr.com",
        "source_post_url": "http://tomhiddles.tumblr.com/post/37231367662",
        "is_indexable": 0,
        "import_datetime": "2013-03-24 01:54:54",
        "trending_datetime": "1970-01-01 00:00:00",
        "images": {
            "fixed_height": {
                "url": "http://media0.giphy.com/media/pWDH6fkHgGHza/200.gif",
                "width": "513",
                "height": "200",
                "size": "271598",
                "mp4": "http://media0.giphy.com/media/pWDH6fkHgGHza/200.mp4",
                "mp4_size": "19808",
                "webp": "http://media0.giphy.com/media/pWDH6fkHgGHza/200.webp",
                "webp_size": "392604"
            },
            "fixed_height_still": {
                "url": "http://media0.giphy.com/media/pWDH6fkHgGHza/200_s.gif",
                "width": "513",
                "height": "200"
            },
            "fixed_height_downsampled": {
                "url": "http://media0.giphy.com/media/pWDH6fkHgGHza/200_d.gif",
                "width": "513",
                "height": "200",
                "size": "530508",
                "webp": "http://media0.giphy.com/media/pWDH6fkHgGHza/200_d.webp",
                "webp_size": "196204"
            },
            "fixed_width": {
                "url": "http://media0.giphy.com/media/pWDH6fkHgGHza/200w.gif",
                "width": "200",
                "height": "78",
                "size": "65057",
                "mp4": "http://media0.giphy.com/media/pWDH6fkHgGHza/200w.mp4",
                "mp4_size": "24950",
                "webp": "http://media0.giphy.com/media/pWDH6fkHgGHza/200w.webp",
                "webp_size": "74208"
            },
            "fixed_width_still": {
                "url": "http://media0.giphy.com/media/pWDH6fkHgGHza/200w_s.gif",
                "width": "200",
                "height": "78"
            },
            "fixed_width_downsampled": {
                "url": "http://media0.giphy.com/media/pWDH6fkHgGHza/200w_d.gif",
                "width": "200",
                "height": "78",
                "size": "100970",
                "webp": "http://media0.giphy.com/media/pWDH6fkHgGHza/200w_d.webp",
                "webp_size": "37622"
            },
            "fixed_height_small": {
                "url": "http://media0.giphy.com/media/pWDH6fkHgGHza/100.gif",
                "width": "256",
                "height": "100",
                "size": "271598",
                "mp4": "http://media0.giphy.com/media/pWDH6fkHgGHza/100.mp4",
                "mp4_size": "170265",
                "webp": "http://media0.giphy.com/media/pWDH6fkHgGHza/100.webp",
                "webp_size": "98852"
            },
            "fixed_height_small_still": {
                "url": "http://media0.giphy.com/media/pWDH6fkHgGHza/100_s.gif",
                "width": "256",
                "height": "100"
            },
            "fixed_width_small": {
                "url": "http://media0.giphy.com/media/pWDH6fkHgGHza/100w.gif",
                "width": "100",
                "height": "39",
                "size": "65057",
                "mp4": "http://media0.giphy.com/media/pWDH6fkHgGHza/100w.mp4",
                "mp4_size": "45670",
                "webp": "http://media0.giphy.com/media/pWDH6fkHgGHza/100w.webp",
                "webp_size": "23380"
            },
            "fixed_width_small_still": {
                "url": "http://media0.giphy.com/media/pWDH6fkHgGHza/100w_s.gif",
                "width": "100",
                "height": "39"
            },
            "downsized": {
                "url": "http://media0.giphy.com/media/pWDH6fkHgGHza/giphy.gif",
                "width": "500",
                "height": "195",
                "size": "1006467"
            },
            "downsized_still": {
                "url": "http://media0.giphy.com/media/pWDH6fkHgGHza/giphy_s.gif",
                "width": "500",
                "height": "195"
            },
            "downsized_large": {
                "url": "http://media0.giphy.com/media/pWDH6fkHgGHza/giphy.gif",
                "width": "500",
                "height": "195",
                "size": "1006467"
            },
            "downsized_medium": {
                "url": "http://media0.giphy.com/media/pWDH6fkHgGHza/giphy.gif",
                "width": "500",
                "height": "195",
                "size": "1006467"
            },
            "original": {
                "url": "http://media0.giphy.com/media/pWDH6fkHgGHza/giphy.gif",
                "width": "500",
                "height": "195",
                "size": "1006467",
                "frames": "12",
                "mp4": "http://media0.giphy.com/media/pWDH6fkHgGHza/giphy.mp4",
                "mp4_size": "84279",
                "webp": "http://media0.giphy.com/media/pWDH6fkHgGHza/giphy.webp",
                "webp_size": "378130"
            },
            "original_still": {
                "url": "http://media0.giphy.com/media/pWDH6fkHgGHza/giphy_s.gif",
                "width": "500",
                "height": "195"
            },
            "looping": {
                "mp4": "http://media.giphy.com/media/pWDH6fkHgGHza/giphy-loop.mp4"
            },
            "preview": {
                "mp4": "http://media3.giphy.com/media/pWDH6fkHgGHza/giphy-preview.mp4",
                "mp4_size": "44332",
                "width": "326",
                "height": "126"
            },
            "downsized_small": {
                "mp4": "http://media3.giphy.com/media/pWDH6fkHgGHza/giphy-downsized-small.mp4",
                "mp4_size": "116662"
            }
        }
    }],
    "meta": {
        "status": 200,
        "msg": "OK",
        "response_id": "5887622069432538bfa2a521"
    },
    "pagination": {
        "total_count": 11258,
        "count": 1,
        "offset": 0
    }
}

1 个答案:

答案 0 :(得分:3)

两个API都会返回一个JSON对象。

json对象通常是这样构造的:

{
    "property1": "value1",
    "property2": "value2"
    "property_array": ["arrayValue1", "arrayValue2"],
    "property_object": {
        "propertyA": "valueA",
        "attributeB": "valueB"
    }
}

所以让我们使用OMDb(例如):

要访问结果,您需要访问“搜索”属性:

var entries = result.Search;

然后,你需要在搜索对象的每个属性上“循环”(whitch也是一个对象):

这样做,你可以使用for ... in循环:

for(var entry_key in entries) {
    // control that property is own by the object (not prototype)
    if(entries.hasOwnProperty(entry_key)) {
        // do whatever you want with the entry
        // To access the entry, use this notation:
        var entry = entries[entry_key];
        // to stay with OMDb example, this should be: 
        var movie_title = entry.Title;
    }
}

var results = {
    "Search": [{
        "Title": "Titanic",
        "Year": "1997",
        "imdbID": "tt0120338",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BZDNiMjE0NDgtZWRhNC00YTlhLTk2ZjItZTQzNTU2NjAzNWNkXkEyXkFqcGdeQXVyNjUwNzk3NDc@._V1_SX300.jpg"
    }, {
        "Title": "Titanic II",
        "Year": "2010",
        "imdbID": "tt1640571",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMTMxMjQ1MjA5Ml5BMl5BanBnXkFtZTcwNjIzNjg1Mw@@._V1_SX300.jpg"
    }, {
        "Title": "Titanic: The Legend Goes On...",
        "Year": "2000",
        "imdbID": "tt0330994",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMTg5MjcxODAwMV5BMl5BanBnXkFtZTcwMTk4OTMwMg@@._V1_SX300.jpg"
    }, {
        "Title": "Titanic",
        "Year": "1953",
        "imdbID": "tt0046435",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMTU3NTUyMTc3Nl5BMl5BanBnXkFtZTgwOTA2MDE3MTE@._V1_SX300.jpg"
    }, {
        "Title": "Raise the Titanic",
        "Year": "1980",
        "imdbID": "tt0081400",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMTY5MTQwNzMxNV5BMl5BanBnXkFtZTcwMzkwOTMyMQ@@._V1_SX300.jpg"
    }, {
        "Title": "The Legend of the Titanic",
        "Year": "1999",
        "imdbID": "tt1623780",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMjMxNDU5MTk1MV5BMl5BanBnXkFtZTgwMDk5NDUyMTE@._V1_SX300.jpg"
    }, {
        "Title": "The Chambermaid on the Titanic",
        "Year": "1997",
        "imdbID": "tt0129923",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMWUzYjgyNDEtNTAyMi00M2JjLTlhMzMtMDJmOGM1ZmYzNzY4XkEyXkFqcGdeQXVyMTA0MjU0Ng@@._V1_SX300.jpg"
    }, {
        "Title": "In Search of the Titanic",
        "Year": "2004",
        "imdbID": "tt1719665",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMTAzNjY0NDA2NzdeQTJeQWpwZ15BbWU4MDIwMzc1MzEx._V1_SX300.jpg"
    }, {
        "Title": "Titanic",
        "Year": "1943",
        "imdbID": "tt0036443",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMTU2Njg4MDgxN15BMl5BanBnXkFtZTcwNzE4MjYyMQ@@._V1_SX300.jpg"
    }, {
        "Title": "S.O.S. Titanic",
        "Year": "1979",
        "imdbID": "tt0079836",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMTMwOTU5MDU0OV5BMl5BanBnXkFtZTcwMDc4OTYyMQ@@._V1_SX300.jpg"
    }],
    "totalResults": "170",
    "Response": "True"
};


var movies_list = document.getElementById('movies-list');

var entries = results.Search;

for(var entry_key in entries) {
	// control that property is own by the object (not prototype)
	if(entries.hasOwnProperty(entry_key)) {
		// do whatever you want with the entry
		// To access the entry, use this notation:
		var entry = entries[entry_key];
		// to stay with OMDb example, this should be: 
       var movie_line = '<p><strong>Title:</strong> ' 
                      + entry.Title + ' (year: ' + entry.Year + ')</p>';
	   movies_list.innerHTML += movie_line;
	}
}
<div id="movies-list">
</div>