1

I need to inject in my page pieces of HTML from external url and I wrote the following simple function for solve cross-domain issue, using Yahoo proxy:

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(/<--[\S\s]*?-->/g, '');
    data = data.replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g, '');
    data = data.replace(/<script[^>]*>[\S\s]*?<\/script>/g, '');
    data = data.replace(/<script.*\/>/, '');
    return data;
}

This works perfectly but I found that some domains reject YQL requests and I can imagine that there are security problem with this approach, too.

So I was wondering if there is a cross-domain solution for .load() in jQuery without using YQL.

Lucifer
  • 29,392
  • 25
  • 90
  • 143
bobighorus
  • 1,152
  • 4
  • 17
  • 35

1 Answers1

1

These are proxy servers (not plugin) that can also help with the cross-domain request:

To fetch the data from google.com, through whateverorigin:

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

Or you can make it through cors-anywhere:

$.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);
});


I strongly recommend you that check out this post: Loading cross domain html page with jQuery AJAX where you will find other ways to overcome the Cross Domain barrier.

There are some jQuery plugins that help with cross-domain requests:

Community
  • 1
  • 1
jherax
  • 5,238
  • 5
  • 38
  • 50