JSON jQuery Question
So I'm trying out JSON for the first time. I have this Twitter API feed that I'm trying to output. Just curious to where I'm going wrong. Attached is my code.
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jq开发者_StackOverflow社区uery-1.4.4.js"></script>
</head>
<body>
<ol class="result"></ol>
<script>
$.getJSON('http://api.twitter.com/1/trends/1105779.json', function(json) {
alert(json.trends.query[1]);
$('.result').html('<li>' + json.trends.query + '</li>');
});
</script>
</body>
</html>
<!-- http://api.twitter.com/1/trends/1105779.json -->
Change the URL to 'http://api.twitter.com/1/trends/1105779.json?callback=?'
.
Your request needs to be JSONP'ed to work around the XHR policy restrictions.
If the URL includes something similar to callback=?
jQuery does its magic to make the request a JSONP request. For more on this: http://api.jquery.com/jQuery.getJSON/
Your problem is that you are trying to access query
as if it were an array. It's not, it's an object. trends
is the actual array. So if you wanted the query
property of the second object in the trends
array, which is what it appears you are trying to do, you'd do this:
var query = json.trends[1].query;
EDIT:
If you are, as a commenter suggests, trying to access the first element in the trends
array, it is at array index 0
. So:
var query = json.trends[0].query;
Your second statement, json.trends.query
is also invalid because trends
is an array, not an object, and has no property query
. If your objective is to get each query
property from all the objects in the trends
array, use jQuery's $.each()
looping construct. Like so:
$.each(json.trends, function(i, result) {
$('.result').append(result.query);
});
You also need to add callback=?
to the end of your query string you pass to $.getJSON()
. jQuery replaces the ?
with a randomly generated function name, which allows jQuery to call your callback function and pass it the data. This implements a JSONP request, which is not subject to the same-origin policy.
Putting it all together:
$.getJSON('http://api.twitter.com/1/trends/1105779.json?callback=?', function(json) {
alert(json.trends[1].query);
$.each(json.trends, function(i, result) {
$('.result').append(result.query);
});
});
Looking at the json returned by the url you gave, you need this:
alert(json.trends[1].query);
trends
is a list of objects, each of which has query
key.
精彩评论