Created
November 5, 2014 19:35
-
-
Save mayfer/1ee58e87b295f1432d0c to your computer and use it in GitHub Desktop.
AJAX examples with Sinatra
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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