Passing hash from perl CGI::Application::Plugin::JSON to jquery form plugin
I need to pass a hash from server side to client side. I am using jquery and perl CGI::Application respectively on the front-end and back-end. I am a starter when it comes to using jquery thus I modified the jquery form plug-in example which shows how to handle JSON data returned from the server http://jquery.malsup.com/form/#j开发者_Python百科son. I tried to use the given code with my favourite perl web framework CGI::Application. The CGI::Application::Plugin::JSON
works well when passing scalar values but due to lack of documentation I can't figure out how to pass arrays or hashes or for that matter complex data structures. When passing a hash I am using the following code snippet :-
foreach my $k (sort keys %hash)
{
return $self->add_json_header ( { message => $hash{$k}} );
}
This is the error I am getting in the apache error log:
ajaxtest.pl: Odd number of elements in hash assignment at /usr/local/share/perl/5.10.0/CGI/Application/Plugin/JSON.pm line 98., referer: http://localhost/echo.html
While passing scalar I am using CGI::Application::Plugin::JSON json_body
function.
Kindly let me know where I am going wrong. Following is the Jquery code in the html file that is also given on the form plugin site (link given above):
// prepare the form when the DOM is ready
$(document).ready(function() {
// bind form using ajaxForm
$('#jsonForm').ajaxForm({
// dataType identifies the expected content type of the server response
dataType: 'json',
// success identifies the function to invoke when the server response
// has been received
success: processJson
});
});
function processJson(data) {
// 'data' is the json object returned from the server
alert(data.message);
}
Any advice on using CGI::Application::Plugin::JSON
with complex data structures likes hashes of hashes and arrays of arrays is most welcome as I would be needing it it in future.
Here's a possible solution.
you will only need the JSON library and in your code you can do the following:
my %data_struct = { a => 1, b => 2 };
my $json = to_json( \%data_struct, {utf8 => 1} );
$json =~ s/"(\d+?)"/$1/g; # to_json puts quotes around numbers, we take them off
# here $self is the CGI::App object, it's probably called like that
$self->header_add( -type => 'application/json' );
return $json;
(As Raoul pointed out, you cannot return more than once in a CGI::App block.)
NOTE: I don't use CGI::Application::Plugin::JSON because I just didn't need it. This way I achieved the same result. Of course, TMTOWTDI. :)
I don't think you understand the CGI::APP return method. You can only return once per runmode.
精彩评论