简体   繁体   English

使用JavaScript和HTML显示API结果

[英]Display API results with JavaScript and HTML

First off, I'm very new to working with APIs at all. 首先,我很擅长使用API​​。 And English is not my first language. 英语不是我的第一语言。 I've searched the web but came up short in finding exactly what I'm looking for, or at least I have not understood enough of what I read to understand how to alter and apply it to my situation. 我已经在网上搜索过了,但却找不到我正在寻找的内容,或者至少我对自己所阅读的知识不够了解,以了解如何改变并应用于我的情况。

I'm working with the Omdb API and the Giphy API, making a silly page. 我正在使用Omdb API和Giphy API,制作一个愚蠢的页面。 I'm using JavaScript and HTML. 我正在使用JavaScript和HTML。

At the end I want the page to display the search result of the user searching for a movie + on-topic gifs. 最后,我希望页面显示用户搜索电影+主题上的GIF的搜索结果。

I've come so far that I have a result from both APIs. 到目前为止,我已经得到了两个API的结果。 That's all good and well. 这一切都很好,很好。 What I don't know how to do is to from these results present, for example, just the movie titles and the .gif-files. 我不知道怎么做的是从这些结果出现,例如,电影标题和.gif文件。 My attempts at splitting the returned results have so far failed. 我分裂返回结果的尝试到目前为止都失败了。 Any suggestions? 有什么建议么? Below is my JavaScript code. 以下是我的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();
  }
}

And below the HTML. 在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>

And here's a sample result from OMDb: 以下是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"
}

And sample result from Giphy: 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
    }
}

Both APIs return you a JSON object. 两个API都返回一个JSON对象。

A json object is generally construct like so: 一个json对象通常是这样构造的:

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

So let use OMDb (for example): 所以让我们使用OMDb(例如):

to access the results, you need to acces the "Search" attribute : 要访问结果,您需要访问“搜索”属性:

var entries = result.Search;

Then, you need to "loop" on each property of the Search object (whitch is also an object) : 然后,您需要在Search对象的每个属性上“循环”(whitch也是一个对象):

to do so, you can use a for...in loop: 为此,您可以使用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": "SOS 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 JavaScript 在 HTML 页面上显示 API 请求的结果 - Display results of an API request on HTML page using JavaScript 如何获取JavaScript查询以HTML显示结果 - How to get JavaScript query to display results in HTML 使用Javascript / PHP / HTML / SQL显示结果和“更多结果”,但不起作用 - Using Javascript/PHP/HTML/SQL to display results and “more results”, but not working 如何在HTML中调用twitter API函数并显示结果? - How to call twitter API function within HTML and display results? 仅使用js在HTML页面中显示API请求结果 - Display API request results in HTML page using only js 如何在HTML中使用JavaScript将复选框结果显示到文本字段和空白区域? - How to Display checkbox results into a textfield and empty area using javascript in html? 如何在 HTML 中显示 JavaScript 函数的结果? - How do I display the results of a JavaScript function in HTML? 无法显示 api 结果 - Unable to display api results Javascript - 将 API 调用的结果循环到 JSON,并以 HTML 格式打印 - Javascript - loop through results from API call to JSON, and print in HTML Javascript和HTML通过Yahoo API显示温度和位置 - Javascript and HTML to display temperature and location from Yahoo API
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM