1

使用 YouTube API。尝试在 json.data.totalItems == 0 时获得警报(“无搜索结果”),但它没有发生,根本没有任何反应......当 json.data.totalItems > 0 时一切正常。

知道为什么会这样吗?

IE

json.data.totalItems == 0: https ://gdata.youtube.com/feeds/api/videos?v=2&alt=jsonc&max-results=20&format=5&orderby=relevance&uploader=partner&q=oierjt

代码:var url = " https://gdata.youtube.com/feeds/api/videos?v=2&alt=jsonc&max- results=20&format=5&orderby=rating&uploader=partner&q=" + searchinput ;

        var request = $.ajax({

            url: url,

            type: "GET",

            timeout: 8000,

            dataType: "json",

            error: function(xhr, ajaxOptions, thrownError) {

                alert("Something went wrong");

            },

            success: function(json) {

                var numberOfItems = json.data.items.length;
        var totalItemsAmount = json.data.totalItems;        

        if (totalItemsAmount == 0) { 
                    alert("No videos found");
                }
                else {

                    for (var i = 0; i < numberOfItems; i++) {
                            alert("videos found")
                        }
                 }
4

1 回答 1

1

检查结果——如果totalItems为零,则items根本不存在。您将在该行得到一个例外json.data.items.length。您需要删除该行,或将其放在else块内:

success: function(json) {
    var totalItemsAmount = json.data.totalItems;        
    if (totalItemsAmount == 0) { 
        alert("No videos found");
    } else {
        var numberOfItems = json.data.items.length;
于 2013-10-25T04:38:13.233 回答