json.data.totalItems == 0无效

时间:2013-10-25 03:22:35

标签: javascript ajax json api youtube

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

知道这是为什么?

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")
                        }
                 }

1 个答案:

答案 0 :(得分:1)

检查results - 如果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;