6

For a project I need to get the source code of web page of different other domains. I have tried following code:

$('#container').load('http://google.com');

$.ajax({
    url: 'http://news.bbc.co.uk',
    type: 'GET',
    success: function(res) {
        var headline = $(res.responseText).find('a.tsh').text();
        alert(headline);
    }
});

Still I am not getting any results but just a blank alert box.

vzwick
  • 11,008
  • 5
  • 43
  • 63
Saurabh Saxena
  • 3,005
  • 10
  • 31
  • 46
  • Here's a link to a similar question with a couple good suggestions (one by me) http://stackoverflow.com/questions/7614420/ajax-jquery-javascript-access-a-page-in-an-external-domain – Aaron Bruce Oct 03 '11 at 18:02

6 Answers6

11

By default all browsers restrict cross-domain requests, you can get around this by using YQL as a proxy. See a guide here: http://ajaxian.com/archives/using-yql-as-a-proxy-for-cross-domain-ajax

Porco
  • 4,163
  • 3
  • 22
  • 25
  • James Padolsey also has a small [jQuery plugin](https://github.com/jamespadolsey/jQuery-Plugins) that uses YQL, if that will make things any easier :) – Mottie Oct 03 '11 at 22:48
4

For security reasons scripts aren't able to access content from other domains. Mozilla has a long article about HTTP access control, but the bottom line is that without the website themselves adding support for cross-domain requests, you're screwed.

Jeremy
  • 1
  • 85
  • 340
  • 366
4

This code is Working Perfectly with the help of JQuery and YQL

$(document).ready(function(){
  var container = $('#target');
  $('.ajaxtrigger').click(function(){
    doAjax($(this).attr('href'));
    return false;
  });
  function doAjax(url){
    if(url.match('^http')){
      $.getJSON("http://query.yahooapis.com/v1/public/yql?"+
                "q=select%20*%20from%20html%20where%20url%3D%22"+
                encodeURIComponent("http://www.yahoo.com")+
                "%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 {
      $('#target').load(url);
    }
  }
  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;
  }
});
Saurabh Saxena
  • 3,005
  • 10
  • 31
  • 46
  • Can't we create something like this functionality in javascript. I am asking this because in future if yahooapi restrict this feature what will happen? – Dev G May 16 '12 at 12:53
  • @Nits Check this .. http://www.frihost.com/forums/vt-32602.html i didn't tried this. BTW don't you think that using jquery is the easiest method. :) – Saurabh Saxena May 17 '12 at 16:10
1

The solution for your case is JSON with padding or JSONP.

You will need an HTML element that specified for its src attribute a URL that returns JSON like this:

<script type="text/javascript" src="http://differentDomain.com/RetrieveUser?UserId=1234">

You can search online for a more in-depth explanation, but JSONP is definitely your solution for this.

oneiros
  • 3,527
  • 12
  • 44
  • 71
0

Do the following steps. 1: Add datatype:jsonp to the script. 2: Add a "callback" parameter to the url 3: Create a javascript function with name same as "callback" param value. 4: The output can be received inside javascript function.

Soumyajit Swain
  • 1,298
  • 1
  • 21
  • 35
-1

Found one more solution for this :

function getData(url){
   if(url.match('^http')){
     $.get(url,
      function(data){
        process(data);
      }//end function(data)
     );//end get
   } 
}

This is really a pretty easier way to handle cross-domain requests. As some of the sites like www.imdb.com rejects YQL requests.

Saurabh Saxena
  • 3,005
  • 10
  • 31
  • 46
  • 1
    I don't think so. It makes no difference to the same origin policy. It won't work. The documentation of jQuery itself says it: "Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol." I don't understand why you accept that wrong answer from yourself... – Thomas Uhrig Aug 17 '13 at 13:04
  • This only works because the query was not cross-domain in the first place, so it is not a valid response to the question. – Chiara Coetzee Sep 29 '13 at 10:12