我有以下脚本,它可以访问jsonp feed并从中获取数据:
$(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;
alert(itemList.count);
/*
var buildHTML = [];
for (var i = 0; i < 5; i++) {
buildHTML.push('<div class="container"><a href="' + itemList[i].link + '" class="title" target="_blank">' + itemList[i].title + '<br /><span class="dateandtime">' + itemList[i].pubDate + '</span></a></div>');
}
$('.portlet-content').empty().append(buildHTML.join('<hr />'))
*/
}
});
}
});
这给了我5
这是正确的。我现在想要获取更多嵌入jsonp的数据,但我遇到了困难。例如,我想得到:
data.query.results.tr.td.div.abbr.title
我将如何得到它?
这是一个返回5的jsfiddle: http://jsfiddle.net/B6hRG/1/
答案 0 :(得分:1)
以下是获取JSONP而不是XML的一些固定代码:
$(document).ready(function() {
get_jsonp_feed();
function get_jsonp_feed() {
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%20%3D%20'http%3A%2F%2Fnews.bbc.co.uk%2Fweather%2Fforecast%2F4276%3F%26search%3Dgerrards%2520cross%26itemsPerPage%3D10%26region%3Dworld%26area%3DGerrards%2520Cross'%20and%20xpath%20%3D%20'%2F%2Ftbody%2Ftr'&format=json&callback=?",
type: 'GET',
dataType: 'jsonp',
error: function(xhr, status, error) {
alert(xhr.responseText);
},
success: function(data) {
var itemList = data.query;
alert(itemList.count);
/*
var buildHTML = [];
for (var i = 0; i < 5; i++) {
buildHTML.push('<div class="container"><a href="' + itemList[i].link + '" class="title" target="_blank">' + itemList[i].title + '<br /><span class="dateandtime">' + itemList[i].pubDate + '</span></a></div>');
}
$('.portlet-content').empty().append(buildHTML.join('<hr />'))
*/
}
});
}
});
要获取data.query.results.tr.td.div.abbr.title
之类的数据,您必须在for
对象上使用data.query.results.tr.td
循环,在兄弟姐妹中使用其他任何循环,或者使用XML并获取原始html,将它放入文档片段并使用jQuery。