2016-08-18 84 views
0

我試圖使用$ .getJSON函數,並且我有2個警報:inside1和內部x2。當我運行該站點時,只處理第一個警報,而代碼從未實際到達第二個警報。我能做些什麼來使代碼處理函數?我真的很感謝幫助我的代碼。

function get_photos(searchtag){ 

    var apikey = '#######################'; 

    alert('inside1'); 

    $.getJSON('api.flickr.com/services/rest/?method=flickr.photos.search&api_key=' + apikey + '&tags=' + searchtag + '&perpage=3&format=json', function (data) { 
     alert('inside x2'); 
}); 

這裏是什麼網址回報(我有雙重檢查是正確的URL幾次):

jsonFlickrApi({ 
     "photos": "page": 1, 
     "pages": 103436, 
     "perpage": 3, 
     "total": "310306", 
     "photo": [{ 
      "id": "28437400284", 
      "owner": "[email protected]", 
      "secret": "711b34701c", 
      "server": "8708", 
      "farm": 9, 
      "title": "20160810-DSC_0158", 
      "ispublic": 1, 
      "isfriend": 0, 
      "isfamily": 0 
     }, { 
      "id": "29058577365", 
      "owner": "[email protected]", 
      "secret": "bd73425d36", 
      "server": "8319", 
      "farm": 9, 
      "title": "20160810-DSC_0159", 
      "ispublic": 1, 
      "isfriend": 0, 
      "isfamily": 0 
     }, { 
      "id": "28437396394", 
      "owner": "[email protected]", 
      "secret": "7de3504657", 
      "server": "8877", 
      "farm": 9, 
      "title": "Sailing", 
      "ispublic": 1, 
      "isfriend": 0, 
      "isfamily": 0 
     }] 
    }, "stat": "ok" 
    }) 
+1

顯示的響應不是JSON,而是JSON-P。如果您檢查瀏覽器控制檯,您應該會看到一條錯誤消息。 – nnnnnn

回答

0

由於@nnnnnn在評論中提到的,你不能使用JSON來通過javascript中的HTTP請求獲取跨域數據。你需要使用JSONP。您需要將$.getJSON(...)替換爲:

$.ajax({ 
    url: 'http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=' + apikey + '&tags=' + searchtag + '&perpage=3&format=json', 
    dataType: 'jsonp', 
    success: function(data) { 
     alert('inside x2'); 
     // You can see the response. 
     alert(data); 
    } 
}); 
+0

非常感謝你= D 如果你不介意,我該如何區分JSON和JSONP? – Stanky

+0

@Stanky高興地幫助:)這個問題的答案提供了一些很好的見解:http://stackoverflow.com/questions/3839966/can-anyone-explain-what-jsonp-is-in-layman-terms – Mike