Skip to content

Instantly share code, notes, and snippets.

@mayfer
Created November 5, 2014 19:35
Show Gist options
  • Save mayfer/1ee58e87b295f1432d0c to your computer and use it in GitHub Desktop.
Save mayfer/1ee58e87b295f1432d0c to your computer and use it in GitHub Desktop.
AJAX examples with Sinatra
require 'sinatra'
require 'open-uri'
require 'sinatra/json'
require 'json'
# sets the view directory correctly (to make it work with gists)
set :views, Proc.new { File.dirname(__FILE__) }
get '/' do
erb :index
end
get '/weather' do
response = {
:city => "Vancouver",
:weather => "still shitty",
:misery => 9,
:date => Date.today
}
# if we had returned "response.to_json" it would have been a raw string being returned
# but when we do "json response", sinatra also automatically changes the content-type header to application/json
json response
end
get '/scrape' do
open('http://google.com') do |response|
response.read
end
end
<!doctype html>
<html>
<head>
<title>ajax example</title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.11.1.min.js'></script>
<script>
$(function(){
$('a').click(function(event){
var query = $('input').val();
$.get("http://en.wikipedia.org/w/api.php?format=json&action=query&titles="+query+"&prop=revisions&rvprop=content", function(response) {
console.log(response);
$('body').html(response);
}, 'jsonp');
});
});
</script>
</head>
<body>
<div id='header'>
<input type='text' /><a href="#">Wikipedia</a>
</div>
<div id='results'>
<h2></h2>
<div class='content'>
</div>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment