开发者

Problem using getJSON and YQL

I'm trying to get the views of a video in Youtube through YQL to display it on my site, I'm using jQuery's $.getJSON method to get the result of the YQL call which I do fine but for some reason the success part isn't firing, here's my code:

$.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DrWlHtvZHbZ8%26feature%3Dplayer_embedded%22%20and%0A%20%20%2开发者_开发技巧0%20%20%20xpath%3D'%2Fhtml%2Fbody%2Fdiv%2Fdiv%5B3%5D%2Fdiv%2Fdiv%2Fdiv%5B3%5D%2Fdiv%2Fdiv%2Fdiv%5B2%5D%2Fdiv%2Fspan%2Fstrong'&format=json&diagnostics=true&callback=cbfunc",
    function(data) {
        alert('Hello');
    }
);

I see on my firebug's console that the request is made and it's returning the correct json object but the alert in my function isn't firing, what am I doing wrong here?

Thanks in advance!


Remove &callback=cbfunc from the URL, so jQuery can define the callback itself.

$.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DrWlHtvZHbZ8%26feature%3Dplayer_embedded%22%20and%0A%20%20%20%20%20%20xpath%3D'%2Fhtml%2Fbody%2Fdiv%2Fdiv%5B3%5D%2Fdiv%2Fdiv%2Fdiv%5B3%5D%2Fdiv%2Fdiv%2Fdiv%5B2%5D%2Fdiv%2Fspan%2Fstrong'&format=json&diagnostics=true",
    function(data) {
        alert('Hello');
    }
);

http://jsfiddle.net/niklasvh/C5cYB/


It is considered bad practice to use jQuery's anonymous callbacks, see Beware of client-side libraries "helping" you on the YQL blog.

Since your original YQL URL told YQL to expect a callback function called cbfunc, then all you need to do is define that function in your JavaScript (in the window scope).

function cbfunc(data) {
    alert('Hello');
}


I know nothing about YQL, but I see an explicit callback set at the end of that querystring, which could be a problem. Have you tried removing "callback=cbfunc", or putting "callback=?" as in the jsonp documentation at http://api.jquery.com/jQuery.getJSON/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜