2011-07-08 38 views
0

我想抓住從https://api.github.com/users/mojombo以下JSON提要:抓住一個遠程JSON飼料和顯示一些值

{ 
    "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": "[email protected]", 
    "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 

}

我有以下的HTML,我想爲值來填充email在頁面加載後:

<div id='github-mojombo'></div> 

我不能得到JQuery的做我想要什麼就做。誠然,我不完全理解回調和/或有很多JQuery的經驗。在下面的示例中,user_email未定義。我究竟做錯了什麼?我將如何改變它,使其在這些DIV中插入電子郵件?

<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> 

回答

1

我會解析響應爲JSON首先試圖響應的訪問屬性之前:

var user_data = JSON.parse(data) 
1
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); 
    }); 
}); 
+0

http://jsfiddle.net/fsB3L/ – Rafay

0

你不能這樣做AJAX請求跨域(它的getJSON本質上只是一個包裝),這只是瀏覽器不允許的。這是回調的地方。你可以做的是使用jQuery的getScript函數爲頁面編寫腳本標籤。回調函數將包裝返回的JSON,以便將腳本標記的內容作爲參數傳遞給JSON的函數。在你的功能中,你然後處理JSON。該守則將是這個樣子:

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"); 
}); 

https://api.github.com/users/mojombo?callback=myCallback的輸出會看起來像:

myCallback('{"name":"foo", "email":"[email protected]", ...rest of the json...}'); 
1

您可以使用以下

function(response) 

var List = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d; $.each(List, function() { this["public_repos"]; });

你有如果它不是0 t,則檢查響應的長度母雞你可以循環使用關鍵詞這個[「columnname」]得到你的結果

希望它會幫助你。