Javascript / API - 搜索结果未显示

时间:2017-01-12 20:53:50

标签: javascript jquery html json giphy-api

我刚开始使用API​​。

我的问题:看起来我的代码在某处不正确。搜索无效。

如何获取用户搜索的特定搜索结果?

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

JS

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

//q = "";

var searchTerm = prompt('Please enter a word :)');
searchTerm = searchTerm.trim().replace(/ /g, "+"); // adds a + wherever a space is

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


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');

     }
        jQuery(function(){
            $("#form-value").keyup(function() {
              var searchTerm = $("#form-value").val().trim().toLowerCase(); 
              $("#here_is_gif").text(value);
            });
        });
};

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

request.send();
});

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>

1 个答案:

答案 0 :(得分:1)

所以问题是你没有在返回数据中使用正确的对象路径:

data = JSON.parse(request.responseText).data;
if(data.length > 0) {
    document.getElementById("here_is_gif").innerHTML = '<center><img src = "'+data[0].images.original.url+'" title="GIF via Giphy"></center>'; // use the first image returned... But data is an array, so you might want to loop over it and add more than one image....
}

此外,你有一个拼写错误:

$("#here_is_gif").text(value); // should be $("#here_is_gif").text(searchTerm);

希望这有帮助!