简体   繁体   中英

JSONP using .getJSON is returning undefined

I'm trying out an exercise in Learning jQuery 4th edition by Karl Swedburg for Ajax, and more specifically JSONP.

My code is

$(document).ready(function(){
var url='https://api.github.com/users/jquery/repos';
$.getJSON(url + '?callback=?',function(data){
  var content='';
  $.each(data,function(index,item){
    content +='<div class="userdata">';
    content +='<div class="username">'+item.id+'</div>';
    content +='<div class="username">'+item.name+'</div>';
    content +='<div class="userurl">'+item.url+'</div>';
    content +='</div>';
  });
  $('#dictionary').append(content);

});
});

I've checked the developer tools and my request is returning status 200

and an extract of the data returned from the request is as shown below

{
  "id": 5999890,
  "name": "2012-dev-summit",
  "full_name": "jquery/2012-dev-summit",
  //more stuff
}

I've checked and double checked my code and can't seem to figure out why is it returning undefined.

EDIT:Added what is appended

undefined
undefined
undefined
undefined
undefined
undefined

i get 6 undefined,which would equate to 2 iterations seeing as outputting 3 items per round, ie. id,name and url.

Try the below. You are getting the result in result.data object. Not in result object.

$(document).ready(function(){
var url='https://api.github.com/users/jquery/repos';
$.getJSON(url + '?callback=?',function(result){
  var content='';
  var data = result.data;
  $.each(data,function(index,item){
    content +='<div class="userdata">';
    content +='<div class="username">'+item.id+'</div>';
    content +='<div class="username">'+item.name+'</div>';
    content +='<div class="userurl">'+item.url+'</div>';
    content +='</div>';
  });
  $('#dictionary').append(content);

});

});

FIDDLE

Try this

$(document).ready(function(){
var url='https://api.github.com/users/jquery/repos';
$.getJSON(url + '?callback',function(data){
  var content='';
  $.each(data,function(index,item){
    content +='<div class="userdata">';
    content +='<div class="username">'+item.id+'</div>';
    content +='<div class="username">'+item.name+'</div>';
    content +='<div class="userurl">'+item.url+'</div>';
    content +='</div>';
  });
  $('#dictionary').append(content);

});
});

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM