Skip to content

Instantly share code, notes, and snippets.

@mayfer
Created October 8, 2014 20:37
Show Gist options
  • Save mayfer/390746c7c2d52be5fdb8 to your computer and use it in GitHub Desktop.
Save mayfer/390746c7c2d52be5fdb8 to your computer and use it in GitHub Desktop.
Ajax examples
require 'sinatra'
require 'nokogiri'
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 :json
end
get '/jsonp' do
erb :jsonp
end
get '/sample' do
"hello world <a href='#'>Another link has appeared</a>"
end
get '/acronym/:acronym' do
open("http://www.nactem.ac.uk/software/acromine/dictionary.py?sf=#{params[:acronym]}") do |f|
response = {
:content => JSON.parse(f.read),
}
return json response
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>
$(document).ready(function(){
$('a').click(function(event){
var url = "/acronym/BMI";
event.preventDefault();
$.get(url, function(response) {
console.log("helloooo", response);
$('#results .content').append(JSON.stringify(response));
}, 'json');
});
});
</script>
</head>
<body>
<div id='header'>
<a href="/sample">Fetch some content</a>
</div>
<div id='results'>
<h2></h2>
<div class='content' style='whitespace: pre;'>
</div>
</div>
</body>
</html>
<!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>
$(document).ready(function(){
// we use submit instead of click to take advantage of things like
// using the enter key to submit
$('form').on('submit', function(e){
e.preventDefault();
var query = $('#query').val();
var url = 'http://en.wikipedia.org/w/api.php?format=json&action=query&titles='+ query +'&prop=revisions&rvprop=content&callback=asd';
$.ajax(url, {
success: function(response) {
for(page in response.query.pages) {
var title = response.query.pages[page].title;
var revision = response.query.pages[page].revisions[0];
var content = revision['*'];
$('#results h2').html(title);
$('#results .content').html(content);
}
$('#results').html();
},
dataType: "jsonp",
});
});
});
</script>
</head>
<body>
<div id='header'>
Search:
<form>
<input type='text' name='query' id='query' />
<input type='submit' name='submit' id='submit' value='Search' />
</form>
</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