I want to grab the following JSON feed from https://api.github.com/users/mojombo:
{
"public_repos": 52,
"type": "User",
"bio": "",
"url": "https://api.github.com/users/mojombo",
"avatar_url": "https://secure.gravatar.com/avatar
/25c7c18223fb42a4c6ae1c8db6f50f9b?d=https:
//gs1.wac.edgecastcdn.net/80460E/assets%2Fimages%2Fgravatars%2Fgravatar-140.png",
"login": "mojombo",
"public_gists": 66,
"following": 11,
"created_at": "2007-10-20T05:24:19Z",
"email": "tom@github.com",
"followers": 2252,
"company": "GitHub, Inc.",
"blog": "http://tom.preston-werner.com",
"name": "Tom Preston-Werner",
"location": "San Francisco",
"html_url": "https://github.com/mojombo",
"hireable": true,
"id": 1
开发者_如何学JAVA
}
I have the following HTML that I want to populate with the value for the email
after the page has loaded:
<div id='github-mojombo'></div>
I can't get the JQuery doing what I want it do do. Admittedly, I don't fully understand callbacks and/or have a lot of experience with JQuery. In the example below, user_email
is undefined. What am I doing wrong? How would I change it to make it insert the email inside those DIVs?
<script>
jQuery(document).ready(function($) {
$.getJSON("https://api.github.com/users/mojombo?callback=?",
function(data) {
var user_data = data;
var user_email = user_data.email;
alert('Got email ' + user_email);
});
});
</script>
I would parse the response as JSON first before trying to access properties of the response:
var user_data = JSON.parse(data)
jQuery(document).ready(function($){
$.getJSON("https://api.github.com/users/mojombo?callback=?", function(data){
var user_email = data.data.email; //note the data.data
alert('Got email ' + user_email);
});
});
you can use the following
function(response)
var List = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
$.each(List, function() {
this["public_repos"];
});
you have to check for the length of the response if it is not 0 then you can loop through and get your result using the key word this["columnname"]
Hope it would help you.
You can't do AJAX requests cross domain (which getJSON is essentially just a wrapper for), it's just not permitted by browsers. This is where the callback comes in. What you can do is write a script tag to the page using jQuery's getScript function. The callback will wrap the JSON coming back so that the content of the script tag is your function with the JSON passed as an argument. Within you function, you then process the JSON. The code would look something like this:
function myCallback(jsonData)
{
// do something with the JSON
var user_data = JSON.parse(data);
var user_email = user_data.email;
alert('Got email ' + user_email);
}
jQuery(document).ready(function($){
$.getScript("https://api.github.com/users/mojombo?callback=myCallback");
});
The output from https://api.github.com/users/mojombo?callback=myCallback
would look something like:
myCallback('{"name":"foo", "email":"foo@bar.com", ...rest of the json...}');
精彩评论