use warnings;
use strict;
use Data::Dumper;
use JSON;
use POE qw(Component::Server::TCP Filter::HTTPD);
use HTTP::Response;
# Load HTTP::Request for forming the initial request.
use HTTP::Request;
use POE qw(Wheel::ReadWrite Filter::Stream);
# Create a JSON object
my $json = new JSON;
POE::Component::Server::TCP->new(
Port => 8088,
ClientFilter => ‘POE::Filter::HTTPD’, ### sub {
my ($kernel, $heap, $request) = @_[KERNEL, HEAP, ARG0];
print Dumper($request);
# It’s a response for the client if there was a problem.
if ($request->isa(“HTTP::Response”)) {
my $response = $request;
$request = $response->request;
warn “ERROR: “, $request->message if $request;
$_[HEAP]{client}->put($response);
$_[KERNEL]->yield(“shutdown”);
return;
}
my $uri=$request->{‘_uri’};
my %query = $uri->query_form;
print “query is “.join(” “,keys %query).” \n”;
#$request = $json->utf8->decode();
my $request_fields = ”;
$request->headers()->scan(
sub {
my ($header, $value) = @_;
$request_fields .= (
”
$header$value
”
);
}
);
my @list = ( 1, 2, \%query );
my $json = new JSON;
my $json_text = $json->encode(\@list);
my $returntext=”$query{‘callback’}($json_text )”;
$heap->{‘message’}=$returntext;
my $response = HTTP::Response->new(200);
$response->push_header( ‘Content-type’, ‘text/javascript’ );
$response->content(
$returntext
);
#print $json_text;
#print Dumper($request);
$_[HEAP]{client}->put($response);
},
);
print “Aim your browser at port 8088 of this host.\n”;
POE::Kernel->run();
exit;
HTML
<script type=”text/javascript”>// <![CDATA[
$(document).ready(function(){
$(“button”).click(function(){
alert(“test”);
$.ajax({
url: “http://localhost:8088/abc.php?xxx=bbbxss“,
// the name of the callback parameter, as specified by the YQL service
jsonp: “callback”,
// tell jQuery we’re expecting JSONP
dataType: “jsonp”,
// tell YQL what we want and that we want JSON
data: {
q: “select title,abstract,url from search.news where query=\”cat\””,
format: “json”
},
// work with the response
success: function( response ) {
console.log( response ); // server response
//var _body = document.getElementsByTagName(‘body’) [0];
//_body.appendChild(response);
}
});
})
})
// ]]></script>
<button>Get JSON data</button>
<div> </div>