2012-06-07 38 views
1

我調用返回一個xmlhttp.responseText看起來像這樣一個FLickrAPI:JavaScript錯誤[jsonFlickrApi沒有定義]

jsonFlickrApi({"photos":{"page":1, "pages":200, "perpage":100, "total":"19934", 
"photo":[{"id":"7315581986", "owner":"[email protected]", "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'?

+0

您是否正確導入包含jsonFlickrApi()函數的js文件?請發佈該代碼和其他任何可以給我們提供更全面照片的代碼。 – ToddBFisher

回答

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 + ")"); 
相關問題