How can I send a JSON response from a Perl CGI program?

前端 未结 3 1838
时光说笑
时光说笑 2020-12-15 18:55

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 thro

3条回答
  •  被撕碎了的回忆
    2020-12-15 19:27

    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.

提交回复
热议问题