使用$ .getJSON方法错误

时间:2016-08-18 04:27:25

标签: javascript jquery json

我正在尝试使用$ .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返回的内容(我已多次将其检查为正确的URL):

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

1 个答案:

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