Giphy API - 如何显示搜索结果中的图像?

时间:2017-01-12 16:28:39

标签: javascript jquery html json giphy-api

Giphy API的GitHub链接位于:https://github.com/Giphy/GiphyAPI

我的问题:因为我是新人,我现在有点卡住了。我从giphy API获取随机gif,而不是用户想要的特定搜索结果。

如何获得用户想要的特定搜索结果而不是随机GIF?

HTML

<h1> Let's Search Some Gifs! </h1>
<div class="info">
    <p> Search below to the wonderful world of Gifs! </p>
        <form class="gif-form">
            <input type="text" id="form-value" class="search-input-rounded">
            <button type="submit" class="search_button"> Search for GIFs </button>
            <input type="reset" value="Reset">
        </form>
        <div class="rando_facts animated bounceIn">
            <p id="here_is_gif"> </p>
        </div>
</div>

JS

document.addEventListener('DOMContentLoaded', function () {

q = "+=";

request = new XMLHttpRequest;
request.open('GET', 'http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag='+q, true);

request.onload = function() {
    if (request.status >= 200 && request.status < 400){
        data = JSON.parse(request.responseText).data.image_url;
        console.log(data);
        document.getElementById("here_is_gif").innerHTML = '<center><img src = "'+data+'"  title="GIF via Giphy"></center>';
    } else {
        console.log('reached giphy, but API returned an error');
     }
};

request.onerror = function() {
    console.log('connection error');
};

request.send();
});

1 个答案:

答案 0 :(得分:0)

在您的js代码段中,您要求的是随机结果,而不是按文字搜索。您的请求中的网址是(注意随机关键字)

http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=

而不是像(取自giphy文档)

http://api.giphy.com/v1/gifs/search?q=funny+cat&api_key=dc6zaTOxFJmzC