Cross-domain queries using jQuery

For the project, I need to get the source code of the web page of various other domains. I tried the 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); } }); 

However, I am not getting any results, but just an empty notification field.

+6
source share
6 answers

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

+11
source

For security reasons, scripts cannot access content from other domains. Mozilla has a long article on HTTP access control , but in the end it turns out that without the site itself adding support for cross-domain requests, you are bolts.

+4
source

This code works fine with 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; } }); 
+4
source

The solution for your case is JSON with an add-on or JSONP.

You will need an HTML element that specifies a URL for the src attribute that returns JSON as follows:

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

You can search the web for a more detailed explanation, but JSONP is definitely your solution to this.

+1
source

Follow these steps. 1: Add data type: jsonp to the script. 2: add the callback parameter to the URL 3: Create a javascript function with a name similar to the value of the callback parameter. 4: The output can be obtained inside the javascript function.

0
source

Found another solution for this:

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

This is really an easier way to handle cross-domain requests. Because some of the sites, such as www.imdb.com, reject YQL queries.

-1
source

Source: https://habr.com/ru/post/898536/


All Articles