我获取图片网址,然后我将此网址插入图片的src,但它没有显示任何图片?我在这里(https://stackoverflow.com/a/12784213/8229192)
遵循了这个想法这是我的代码:
HTML:
<h1>Gif image search</h1>
<div id="problemform" class="form-inline">
<input id="probleminput" class="form-inline" placeholder="Enter your keyword" type="text" style="display: inline;"></input>
<button id="problemsubmit" class="btn" style="display: inline-block;">Submit</button>
</div>
<div>Showing <h2 id="resultCount">0</h2>results<div>
<img src="" id="picture"/>
js code:
$('#problemsubmit').on('click', function(event) {
event.preventDefault();
var formInput = $('#probleminput').val();
var xhr = $.get("http://api.giphy.com/v1/gifs/search?q=" + formInput + "&api_key=o1H3Da15oqhgM3WlAhPnQYJV8g9l3NdV&limit=6");
xhr.done(function(data) {
console.log("success got data", data);
$('#resultCount').html(data.data.length);
var imageString = data.data[0].url + "";
$('#picture').attr('src', imageString);
}
);
});
答案 0 :(得分:4)
您在Giphy API中使用的url
参数链接到其网站上展示图片的页面。该参数并不意味着嵌入。
您需要向下钻取数据以查找可以实际嵌入图像的GIF网址。您需要从数组中选择一个大小并使用url
,而不是使用images.[size].url
。
在Giphy的API文档中了解图像对象:
https://developers.giphy.com/docs/#images-object
以下是使用original
尺寸GIF的实时示例:
$('#problemsubmit').on('click', function(event) {
event.preventDefault();
var formInput = $('#probleminput').val();
var xhr = $.get("https://api.giphy.com/v1/gifs/search?q=" + formInput + "&api_key=o1H3Da15oqhgM3WlAhPnQYJV8g9l3NdV&limit=6");
xhr.done(function(data) {
$('#resultCount').html(data.data.length);
var imageString = data.data[0].images.original.url;
$('#picture').attr('src', imageString);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Gif image search</h1>
<div id="problemform" class="form-inline">
<input id="probleminput" class="form-inline" placeholder="Enter your keyword" type="text" style="display: inline;" value="hello"></input>
<button id="problemsubmit" class="btn" style="display: inline-block;">Submit</button>
</div>
<div>Showing
<h2 id="resultCount">0</h2>results
<div>
<img src="" id="picture" />
</div>
</div>