jQueryとWEBrickでJSONP

以下を組み合わせてゴニョゴニョしてJSONPを試してみたメモ。


Webサーバー側はこんな感じ。

require 'rubygems'
require 'activesupport'
require 'webrick/httpserver'

s = WEBrick::HTTPServer.new(:Port=>8888)
trap("INT") { s.shutdown }
s.mount_proc("/users") do |req, res|
  res.content_type = "text/json"
  params = {}
  req.query_string.split('&').map do |p|
    params[$1.intern] = $2 if /(\w+)=(\w+)/ =~ p
  end
  users = {
    :katsuo => { :name => 'isono katsuo', :age => 11},
    :tarao  => { :name => 'fuguta tarao', :age =>  3},
  }
  res.body = "#{params[:callback]}(#{users[params[:id].intern].to_json})"
end
s.start

HTMLのほうはこう。

<html>
<head>
<script src='jquery-1.2.6.js'></script>
<script type='text/javascript'>
$(function() {
  $('#trigger').click(function() {
    $.ajax({
      url :      "http://192.168.0.5:8888/users",
      dataType : "jsonp",
      data :     { id : "katsuo" },
      success :  function(j) {
        var user = j.name + '(' + j.age + ')';
        $('#target').html('<p>' + user + '</p>');
      },
      error : function(){ alert('error'); }
    })
  });
});
</script>
</head>
<body>
<div id='target'><p>who am i ?</p></div>
<input type='button' id='trigger' value='click me' />
</body>
</html>

数日前からjQueryを使い始めたんだけどとても快適。1.2.6からposition()も入って位置の取得も簡単だ。