Skip to content

Instantly share code, notes, and snippets.

@axross
Last active January 3, 2016 03:08
Show Gist options
  • Save axross/8399774 to your computer and use it in GitHub Desktop.
Save axross/8399774 to your computer and use it in GitHub Desktop.
Ajax経由でセッションの内容を取得するテスト
# Ajax経由でセッションの内容を取得するテスト
require 'sinatra'
require 'sinatra/json'
set sessions: true
get '/' do
erb :index
end
get '/ajax/set_name/:name' do
session[:name] = params[:name]
''
end
get '/ajax/get_session' do
json(session_string: request.cookies['rack.session'])
end
get '/ajax/get_name/:session_string' do
sessions = Rack::Session::Cookie::Base64::Marshal.new.decode(params[:session_string])
json(name: sessions['name'])
end
__END__
@@index
<!doctype html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>Ajax経由でセッションの内容を取得するテスト</title>
</head>
<body>
<h1>Ajax経由でセッションの内容を取得するテスト</h1>
<input id="input" type="text" placeholder="name"> <a id="set_name" href="#">この名前で登録</a><br><br>
<a id="get_session" href="#">セッション文字列を取得</a><br><br>
<a id="get_name" href="#">名前を取得</a> : <span id="name"></span>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script>
$(function() {
var session_string = '';
$('#set_name').click(function() {
$.get('ajax/set_name/' + $('#input').val());
});
$('#get_session').click(function() {
$.getJSON('ajax/get_session', function(data) {
session_string = data['session_string'];
console.log(data);
});
});
$('#get_name').click(function() {
$.getJSON('ajax/get_name/' + session_string, function(data) {
$('#name').text(data['name']);
console.log(data);
});
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment