2

我调用了一个 FlickrAPI,它返回xmlhttp.responseText如下所示:

jsonFlickrApi({"photos":{"page":1, "pages":200, "perpage":100, "total":"19934",
 "photo":[{"id":"7315581986", "owner":"62691288@N00", "secret":"504915125a", 
"server":"7090", "farm":8, "title":"China, Tiananmen Square", "ispublic":1,
 "isfriend":0, "isfamily":0}, {"id":"7308693706",
...

我尝试像这样解析它:

var jsonResponse = xmlhttp.responseText ;
jsonResponse = eval("("+jsonResponse + ")");
var output += jsonResponse.photos.photo[1].id ;
alert(output);

萤火虫告诉我:jsonFlickrApi is not defined

  • 为什么我会收到此错误消息?

  • 为什么我必须首先使用'eval'?

4

1 回答 1

4

似乎您得到了对您的请求的JSONP响应,而不是 JSON 响应。JSONP是一个 JSON 对象,包装在一个函数调用中。所以只需定义函数jsonFlickrApi,它会在响应可用时调用:

function jsonFlickrApi (response) {
  console.log(
     "Got response from Flickr-API with the following photos: %o", 
     response.photos
  );
  // Handle the response here. I.E update the DOM, trigger event handlers etc.
}

// Later in your XMLHttpRequest code:
var jsonResponse = xmlhttp.responseText ;
// This will call the jsonFlickrApi-function.
eval("("+jsonResponse + ")");
于 2012-06-07T20:51:45.053 回答