Skip to content

Instantly share code, notes, and snippets.

@hallettj
Created July 23, 2009 00:52
Show Gist options
  • Save hallettj/152418 to your computer and use it in GitHub Desktop.
Save hallettj/152418 to your computer and use it in GitHub Desktop.
<!-- This is an example of how to make cross site Ajax requests using the new
W3C Access Control API described at:
https://developer.mozilla.org/En/HTTP_Access_Control
This is the client-side implementation. Use the cs_xhr and cs_load functions to
perform cross-site Ajax requests. -->
<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
function cs_xhr(url, data, callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
callback(xhr.responseText, xhr.status);
}
}
xhr.send(null);
}
function cs_load(url, data) {
cs_xhr(url, data, function(responseText, responseStatus) {
if (responseStatus == 200) {
$('#main').text([responseText, responseStatus].join(', '));
} else {
$('#main').text(['ERROR', responseStatus].join(', '));
}
});
}
</script>
<title>Cross-site Ajax Test</title>
</head>
<body>
<h1>Test</h1>
<div id="main"></div>
</body>
</html>
# This is an example of how to make cross site Ajax requests using the new W3C
# Access Control API described at:
# https://developer.mozilla.org/En/HTTP_Access_Control
# This is the server-side implementation using Ruby on Sinatra:
require 'sinatra'
# OPTIONS requests may be received as 'preflight' access control.
before do
if request.request_method == "OPTIONS"
headers['Access-Control-Allow-Origin'] = '*'
halt 200, "Yes, cross-site requests are allowed."
end
end
# This action may be requested cross-site / cross-domain.
get '/' do
headers['Access-Control-Allow-Origin'] = '*'
"Hello, world!"
end
# This action may be requested from this domain only.
get '/no-cross-site' do
"*Grump*"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment