[英]Extracting data from a GET response/JSON object
Haven't touched Javascript for a bit while and cannot find a proper way to extract data from a JSON object. 有一阵子没接触过Javascript,也找不到从JSON对象提取数据的正确方法。 So I am basically sending a simple GET request to the Giphy API and attempting to get URL's from the response but for some reason I get all kinds of errors.
因此,我基本上是向Giphy API发送一个简单的GET请求,并尝试从响应中获取URL,但是由于某种原因,我会遇到各种错误。 This is what I tried:
这是我尝试的:
$(function() { $('#searchButton').click(function() { console.log("test"); $("#result").append("test<br />"); var xhr = $.get("http://api.giphy.com/v1/gifs/search?q=cats&api_key=dc6zaTOxFJmzC&limit=1"); xhr.done(function(data) { console.log(this.fixed_height); $("#result").append("success got data<br />" + data + "<br />"); console.log("success got data", data); $.each(data.results, function() { $.each(this.images, function() { console.log(this.fixed_height); $("#result").append(this.fixed_height + "<br />"); }); }) }); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <button id="searchButton">search!</button> <div id="result"></div>
You have a couple of problems. 你有几个问题。 First, there is not a
results
member in the data
object. 首先,
data
对象中没有results
成员。 The only thing I see that you can iterate on, in the data object is yet another data
member. 我看到的唯一可以迭代的内容是数据对象中的另一个
data
成员。 Second, inside the images
, there is no fixed_height
, just height
. 其次,在
images
内部,没有fixed_height
,只有height
。 This works: 这有效:
var xhr = $.get("http://api.giphy.com/v1/gifs/search?q=cats&api_key=dc6zaTOxFJmzC&limit=1");
xhr.done(function (data) {
$.each(data.data, function () {
$.each(this.images, function () {
console.log(this.height);
});
})
});
http://jsfiddle.net/n9ffva83/ http://jsfiddle.net/n9ffva83/
Remember $(function () {});
记住
$(function () {});
is not needed in JSFiddle, so you must provided (just the way you do in the code you gave us above). JSFiddle中不需要,因此您必须提供(就像您在上面提供给我们的代码中所做的那样)。
EDIT : To just get the url of the fixed height try this: 编辑 :要获取固定高度的网址,请尝试以下操作:
var xhr = $.get("http://api.giphy.com/v1/gifs/search?q=cats&api_key=dc6zaTOxFJmzC&limit=1");
xhr.done(function (data) {
$.each(data.data, function () {
console.log(this.images.fixed_height.url);
})
});
It seems this url is only one, that belong to the images. 看来这个网址只是一个,属于图片。
http://jsfiddle.net/n9ffva83/1/ http://jsfiddle.net/n9ffva83/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.