【问题标题】:Javascript/API - Search result not showingJavascript/API - 搜索结果未显示
【发布时间】:2017-05-28 03:01:54
【问题描述】:

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

【问题讨论】:

    标签: javascript jquery html json giphy-api


    【解决方案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);
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2023-04-07
      • 2021-02-23
      • 1970-01-01
      • 1970-01-01
      • 2021-09-24
      • 2011-05-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多