如何从Perl CGI程序发送JSON响应?

Rak*_*esh 20 javascript perl json

我正在编写一个来自perl/cgi程序的JSON响应.标题的内容类型必须是"application/json".但它似乎没有被识别为响应被抛出作为文本文件.

我将使用jQuery的JSON库捕获响应.我在发送JSON响应时遗漏了哪里.

Bri*_*anH 28

我在perl/cgi程序中这样做.

我在我的代码顶部使用这些:

use CGI qw(:standard);
use JSON;
Run Code Online (Sandbox Code Playgroud)

然后我打印json标题:

print header('application/json');
Run Code Online (Sandbox Code Playgroud)

这是一种内容类型:

Content-Type: application/json
Run Code Online (Sandbox Code Playgroud)

然后我打印出这样的JSON:

my $json->{"entries"} = \@entries;
my $json_text = to_json($json);
print $json_text;
Run Code Online (Sandbox Code Playgroud)

我的javascript调用/处理它像这样:

   $.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() {
        }
    });
Run Code Online (Sandbox Code Playgroud)

如果您不想安装它,则不一定必须使用JSON库,您可以直接打印JSON格式的文本,但它可以轻松地将perl对象转换为JSON prety.