javascript错误[jsonFlickrApi未定义]

时间:2012-06-07 20:15:47

标签: javascript json api flickr

我调用一个返回xmlhttp.responseText的FLickrAPI,如下所示:

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

Firebug告诉我:jsonFlickrApi is not defined

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

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

1 个答案:

答案 0 :(得分: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 + ")");