1

我正在尝试通过 facebook Graph API 获取照片。这是我的代码:

function getImgURL(photos, m) {
  n=0;
  while (typeof photos[n] !== 'undefined') {
    photourl[m] = photos[n].images[2].source;
    n++;
    m++;
  }
}

$('document').ready(function() {
  var url = "https://graph.facebook.com/179877662120200";
  var json = $.ajax(url);
  console.log(json);
  console.log(json.responseText);
  var photos = $.parseJSON(json);
  console.log(photos);
  console.log(photos);
  var m = 0;
  getImgURL(photos, m);
  while (typeof photos.paging !== 'undefined') {
    json = $.ajax(photos.paging.next);
    photos = $.parseJSON(json);
    getImgURL (photos, m);
  }
});

所以查看日志,它将变量 json 作为对象返回。该对象的一个​​属性是“responseText”,但是当我尝试将其打印到控制台时,它返回“未定义”

4

2 回答 2

3

AJAX/JSON-P 请求是(通常 - 总是在 JSON-P 的情况下)异步操作 - 您需要在回调中接收和处理响应,而不是在请求之后。

你认为你得到的对象实际上是 jQuery 生成的延迟对象,而不是响应。

所以:

$.getJSON(url).done(function(response) {
    console.log(response); //here's your response
});

或者,如果您出于某种原因希望稍后声明回调:

var req = $.getJSON(url);
//other, synchronous code here
req.done(function(response) { console.log(response); });

其他几点:

1) jQuery 自动解析作为 JSON-P 请求的一部分返回的 JSON 字符串,因此您不需要像现在这样自己解析它

2)你的nvar 是(看似)全球性的

3)你可能想改进你的缩进,因为代码不是超级可读

4)您的循环可以简化为while(photos[n]) {...

于 2012-07-30T17:20:21.560 回答
2
var json = $.ajax({
    'url': "https://graph.facebook.com/179877662120200",
    'success': function(json) {
        console.log(json);
        console.log(json.responseText);
    }
});
于 2012-07-30T17:24:31.127 回答