I know about AJAX cross-domain policy. So I can\'t just call \"http://www.google.com\" over a ajax HTTP request and display the results somewhere on my site.
I tried
I faced the same problem during 2 days and I found the solution, and it's elegant after googling a lot. I needed xss Ajax for some widget clients which pull datastream from tiers websites to my Rails app. here's how I did.
If you are using a php script to get the answer from the remote server, add this line at the begining:
header("Access-Control-Allow-Origin: *");
The only (easy) way to get cross-domain data using AJAX is to use a server side language as the proxy as Andy E noted. Here's a small sample how to implement that using jQuery:
The jQuery part:
$.ajax({
url: 'proxy.php',
type: 'POST',
data: {
address: 'http://www.google.com'
},
success: function(response) {
// response now contains full HTML of google.com
}
});
And the PHP (proxy.php):
echo file_get_contents($_POST['address']);
Simple as that. Just be aware of what you can or cannot do with the scraped data.
You will need to dynamically insert a script tag into the page that references the data. Using JSONP, you can execute some callback function when the script has loaded.
The wikipedia page on JSONP has a concise example; the script tag:
<script type="text/javascript" src="http://domain1.com/getjson?jsonp=parseResponse">
</script>
would return the JSON data wrapped in a call to parseResponse
:
parseResponse({"Name": "Cheeso", "Rank": 7})
(depending on the configuration of the getjson
script on domain1.com)
The code to insert the tag dynamically would be something like:
var s = document.createElement("script");
s.src = "http://domain1.com/getjson?jsonp=parseResponse";
s.type = "text/javascript";
document.appendChild(s);
You can use the technology CORS to configure both servers (the server where the Javascript is running and the external API server)
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
p.s.: the answer https://stackoverflow.com/a/37384641/6505594 is also suggesting this approach, and it's opening the external API server to everyone else to call it.