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.