javascript - 使用 YQL 与 JQuery 进行跨域请求

标签 javascript jquery cross-domain yql

所以我需要发出一个跨域请求,其中响应不是 JSON 格式,所以我不能使用 .getJSON。 .get 显然不起作用,因为它是跨域请求。

我在谷歌搜索时遇到了这个( Read this ),它似乎应该适合我想做的事情(即使用 jquery 插件进行非 json 格式的跨域调用)。我的代码如下所示。我知道该网址工作正常,因为如果我将其粘贴到浏览器中,我可以看到响应,根据 last.fm 文档

The body of the server response consists of a series of \n (ASCII 10) terminated lines. A typical successful server response will be something like this:

OK
17E61E13454CDD8B68E8D7DEEEDF6170
http://post.audioscrobbler.com:80/np_1.2
http://post2.audioscrobbler.com:80/protocol_1.2

所以我知道我的网址没问题。现在我想知道如何获取这些信息,以及为什么我的示例版本不起作用。

function performHandshake(sk, token, ts){

    var token = md5(apiSecret + ts);
    var urlToUse = "http://post.audioscrobbler.com/?hs=true&p=1.2.1&c=tst&v=1.0&u=chamals&t=" + ts + "&a=" + token + "&api_key=" + apiKey + "&sk=" + sk + "&format=xml&callback=cbfunc";
            $('#container').load(urlToUse);
    $.ajax({
        url: urlToUse,
        type: 'GET',
        success: function(res){
            var headline = $(res.responseText).find('a.tst').text();
            window.console.log(headline);   
        }   
    });

}

最佳答案

您链接的页面讨论了使用 YQL 和 jQuery。这是一个非常有趣的解决方案。但是,您的示例似乎跳过了 YQL 部分(这很重要)。

var urlToUse = "http://post.audioscrobbler.com/?hs=true&p=1.2.1&c=tst&v=1.0&u=chamals&t=" + ts + "&a=" + token + "&api_key=" + apiKey + "&sk=" + sk + "&format=xml&callback=cbfunc";

var yqlUrl2Use = "http://query.yahooapis.com/v1/public/yql?"+
            "q=select%20*%20from%20html%20where%20url%3D%22"+
            encodeURIComponent(urlToUse)+
            "%22&format=xml'&callback=?"
    // this function gets the data from the successful 
    // JSON-P call

然后您必须将新 URL 作为 JSONP 请求进行调用...

$.getJSON(yqlUrl2Use, function(json){
    // figure out the format of the answer here...   
});

关于javascript - 使用 YQL 与 JQuery 进行跨域请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3206753/

相关文章:

Javascript:使用 id 从 php 脚本中提取正确的 json

events - 使用点击事件从 iframe 向父级发送消息

javascript - 是否可以从 HTTPS 向 HTTP 发出 JSONP 请求?

javascript - Firebase 多次登录用户

javascript - WebStorm diff 中一行上的黄色 block 是什么意思?

javascript - Adobe AIR 和多个 XMLHttpRequest ……很奇怪

javascript - 在手持/智能设备上使用不同浏览器时的屏幕宽度问题

javascript - 如何选择文字?

javascript - 第一次成功提交后提交停止工作

WPF:如何将数据从另一个域编码到用户控件