I am writing a JSON response from a perl/cgi program. The header's content type needs to be "application/json". But it doesn't seems to be recognized as response is thrown as a text file.
I would be capturing response using JSON library of jQuery. Where am I missing in sending the JSON response.
Decoding JSON in Perl (decode_json)Perl decode_json() function is used for decoding JSON in Perl. This function returns the value decoded from json to an appropriate Perl type.
While CGI scripts can be written in many different programming languages, Perl is commonly used because of its power, its flexibility and the availability of preexisting scripts. sent to the server through CGI, the results may be sent to the client.
I am doing this in a perl/cgi program.
I use these in the top of my code:
use CGI qw(:standard);
use JSON;
Then I print the json header:
print header('application/json');
which is a content type of:
Content-Type: application/json
And then I print out the JSON like this:
my $json->{"entries"} = \@entries;
my $json_text = to_json($json);
print $json_text;
My javascript call/handles it like this:
$.ajax({
type: 'GET',
url: 'myscript.pl',
dataType: 'json',
data: { action: "request", last_ts: lastTimestamp },
success: function(data){
lastTs = data.last_mod;
for (var entryNumber in data.entries) {
//Do stuff here
}
},
error: function(){
alert("Handle Errors here");
},
complete: function() {
}
});
You don't necessarily have to use the JSON library if you don't want to install it, you could print straight JSON formatted text, but it makes converting perl objects to JSON prety easy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With