0

I am trying to get the HTML of an external url with jQuery but I cannot get the code below to work.

Can any one tell me how to make this work?

<script language="javascript" type="text/javascript">
$.ajax({
    url: 'http://news.bbc.co.uk',
    type: 'GET',
    success: function(res) {
        var headline = $(res.responseText).find('a.tsh').text();
        alert(headline);
    }
});
</script>
idmean
  • 14,540
  • 9
  • 54
  • 83
user3746002
  • 43
  • 1
  • 3
  • 8
  • 2
    Cross-site access stops you lifting unauthorized content from other sites. If you really want to do this, do it server-side, so you have full control over the feed your page uses. When in doubt, use a tool like Fiddler2 (http://www.telerik.com/fiddler) to see what is being returned by the remote server to your page/script. – iCollect.it Ltd Aug 18 '14 at 09:24

1 Answers1

-2
// Accepts a url and a callback function to run.
function requestCrossDomain( site, callback ) {

// If no url was passed, exit.
if ( !site ) {
    alert('No site was passed.');
    return false;
}

// Take the provided url, and add it to a YQL query. Make sure you encode it!
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + site + '"') + '&format=xml&callback=cbFunc';

// Request that YSQL string, and run a callback function.
// Pass a defined function to prevent cache-busting.
$.getJSON( yql, cbFunc );

function cbFunc(data) {
// If we have something to work with...
if ( data.results[0] ) {
    // Strip out all script tags, for security reasons.
    // BE VERY CAREFUL. This helps, but we should do more. 
    data = data.results[0].replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');

    // If the user passed a callback, and it
    // is a function, call it, and send through the data var.
    if ( typeof callback === 'function') {
        callback(data);
    }
}
// Else, Maybe we requested a site that doesn't exist, and nothing returned.
else throw new Error('Nothing returned from getJSON.');
}
}

Call the Function

requestCrossDomain('http://www.cnn.com', function(results) {
   $('#container').html(results);
});
  • Please [avoid link only answers](http://meta.stackoverflow.com/tags/link-only-answers/info). Answers that are "barely more than a link to an external site” [may be deleted](http://stackoverflow.com/help/deleted-answers). – Quentin Aug 18 '14 at 09:31
  • For some reason this doesn't work. what JQUERY references are you using in your script? – user3746002 Aug 18 '14 at 10:28
  • [http://code.tutsplus.com/tutorials/quick-tip-cross-domain-ajax-request-with-yql-and-jquery--net-10225] – Vikas Satpute Aug 18 '14 at 10:49