���ؤκ�ȯ���Τ褦�ʵ��⤹��Τ����ɡ�XML->JSONP Gateway ����礳�äȤ������Ƥߤޤ�����

xml2jsonp.cgi
#!/usr/local/bin/perl -T
#
# $Id: xml2jsonp.cgi,v 0.1 2006/09/26 15:00:37 dankogai Exp dankogai $
#
use strict;
use warnings;
use LWP::UserAgent;
use XML::Simple;
use JSON::Syck;
use CGI;

my $timeout = 15;            # seconds;
my $max_size = 1024 * 1024;  # bytes;

my $q = CGI->new();
my $uri = $q->param('uri') or error($q, 400);
my $callback = $q->param('callback') || 'jsonp';

error($q, 400) unless $uri =~ /^http:/;
my $ua = LWP::UserAgent->new(timeout => $timeout, max_size => $max_size);
my $res = $ua->get($uri);
error($q, $res->code) unless $res->is_success;
error($q, 400) unless $res->header('Content-Type') =~ /xml/;
my $obj = XMLin( $res->content);

print 
    $q->header(-type => 'application/x-javascript; charset=utf-8'),
    $callback, '(', JSON::Syck::Dump($obj), ");\n";

sub error{
    my ($q, $status) = @_;
    $status ||= 502;
    print $q->header(-status => $status);
    exit();
}

__END__

LWP,XML::Simple,������JSON::Syck�˰�¸���ޤ����������Τ������Ǥ��äȤ�����˽񤱤ޤ�����

�㤨�С�����ʻȤ���������ޤ���


client source
<script language="JavaScript"
 src="http://www.kawa.net/works/js/jkl/share/jkl-dumper.js"></script>
<script>
function XML2JSONP(proxy, cb){
  this.proxy = proxy;
  this.cb    = (cb || 'jsonp');
  this.parse = function(uri, cb){
    if (! cb) cb = this.cb;
    var script = document.createElement('script'); 
    script.id = this.proxy + '?uri=' + encodeURIComponent(uri) + '&callback=' + cb;
    script.charset = 'UTF-8';
    script.src = script.id; 
    document.lastChild.appendChild(script);
    // document.lastChild.removeChild(script);
  };
  return this;
}

function $(id){ return document.getElementById(id) }
var xml2jsonp = new XML2JSONP('http://www.dan.co.jp/~dankogai/cgi/xml2jsonp.cgi');
function jsonp(json){
  $('json').innerHTML = (new JKL.Dumper()).dump(json)
}
</script>
<div style="border: dotted 1px; padding: 0.25em">
<input type="text" id="uri" size="64"
 value="http://reader.livedoor.com/recommend/alpha_bloggers.xml">
<input type="submit" onclick="xml2jsonp.parse($('uri').value)" >
<input type="submit" onclick="json.innerHTML=''" value="clear json">
<pre id="json">
</pre>
</div>

Enjoy!

Dan the Javascripting Perl Monger