难以循环遍历JSONP数据

时间:2011-06-13 10:04:55

标签: json jquery jsonp

我有以下脚本,它似乎只从循环的第一次迭代中获取值,而不是其余的:

$(document).ready(function() {
    get_jsonp_feed();

    function get_jsonp_feed() {
        $.ajax({
            url: "http://query.yahooapis.com/v1/public/yql?q=%20SELECT%20*%20FROM%20html%20WHERE%20url%3D%22http%3A%2F%2Fnews.bbc.co.uk%2Fweather%2Fforecast%2F4276%3Fsearch%3Dgerrards%2520cross%26itemsPerPage%3D10%26region%3Dworld%26area%3DGerrards%2520Cross%22%20and%20xpath%20%3D%20'%2F%2Ftable%2Ftbody%2Ftr'&format=json&diagnostics=true&callback=cbfunc",
            type: 'GET',
            dataType: 'jsonp',
            jsonp: 'callback',
            jsonpCallback: 'cbfunc',
            error: function(xhr, status, error) {
                alert(xhr.responseText);
            },
            success: function(data) { 
                var itemList = data.query.results.tr[0].td;

                for (var i = 0; i < 5; i++) {
                    alert(itemList[i].div.abbr.content);
                }
            }
        });
    }
});

这会显示Mon,之后会显示Cannot read property 'content' of undefined。它应该显示5个提醒,MonTueWedThuFri

jsfiddle:http://jsfiddle.net/DsEGT/

2 个答案:

答案 0 :(得分:0)

您希望循环遍历tr元素,而不是td元素。进行success回调:

            var itemList = data.query.results.tr;

            for (var i = 0; i < 5; i++) {
                alert(itemList[i].td[0].div.abbr.content);
            }

答案 1 :(得分:0)

你应该循环完成这些日子并获得每天的第一个属性,而不是在第一天循环属性:

var itemList = data.query.results.tr;

for (var i = 0; i < 5; i++) {
  alert(itemList[i].td[0].div.abbr.content);
}