jquery.load()避免了没有YQL的跨域问题



我需要从外部url在我的页面中注入HTML片段,我使用Yahoo代理编写了以下简单函数来解决跨域问题:

function crossDomainAjaxLoad(url, selector) {
    container = $('#container');
    if (url.match('^http')) {
        $.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodeURIComponent(url) + "%22&format=xml'&callback=?", function (data) {
            if (data.results[0]) {
                var data = filterData(data.results[0]);
                container.html(data);
            } else {
                var errormsg = '<p>Error: could not load the page.</p>';
                container.html(errormsg);
            }
        });
    } else {
        container.load(url, function () {});
    }
}
function filterData(data) {
    data = data.replace(/<?/body[^>]*>/g, '');
    data = data.replace(/[r|n]+/g, '');
    data = data.replace(/<--[Ss]*?-->/g, '');
    data = data.replace(/<noscript[^>]*>[Ss]*?</noscript>/g, '');
    data = data.replace(/<script[^>]*>[Ss]*?</script>/g, '');
    data = data.replace(/<script.*/>/, '');
    return data;
}

这非常有效,但我发现有些域拒绝YQL请求,我可以想象这种方法也存在安全问题。

所以我想知道在jQuery中是否有一个不使用YQL的.load()跨域解决方案。

这些是代理服务器(而不是插件),也可以帮助跨域请求:

  • Whateverorigin.org
  • Cors任意位置

要从google.com,通过whateverorigin获取数据:

$.getJSON('http://whateverorigin.org/get?url=' + /*proxy server*/
          encodeURIComponent('http://google.com') + '&callback=?',
          function (data){
            console.log("> ", data);
            $("#viewer").html(data.contents);
});

或者,您可以在任何地方通过cors

$.get(
    'http://cors-anywhere.herokuapp.com/' + /*proxy server*/
    'http://en.wikipedia.org/wiki/Cross-origin_resource_sharing',
    function (response) {
        console.log("> ", response);
        $("#viewer").html(response);
});


我强烈建议您查看这篇文章:使用jQuery AJAX加载跨域html页面,在那里您将找到克服跨域障碍的其他方法。

有一些jQuery插件可以帮助处理跨域请求:

  • 使用YQL和jQuery的跨域AJAX请求
  • 使用jQuery.ajax的跨域请求

最新更新