0

我是使用 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>
4

1 回答 1

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

希望这可以帮助!

于 2017-01-12T21:22:02.650 回答