如何从Perl CGI程序发送JSON响应? [英] How can I send a JSON response from a Perl CGI program?

查看:150
本文介绍了如何从Perl CGI程序发送JSON响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

I would be capturing response using JSON library of jQuery. Where am I missing in sending the JSON response.

推荐答案

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

I am doing this in a perl/cgi program.

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

I use these in the top of my code:

use CGI qw(:standard);
use JSON;

然后我打印json标题:

Then I print the json header:

print header('application/json');

这是一种内容类型:

Content-Type: application/json

然后我打印像这样出JSON:

And then I print out the JSON like this:

my $json->{"entries"} = \@entries;
my $json_text = to_json($json);
print $json_text;

我的javascript电话/处理方式如下:

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() {
        }
    });

如果你不想安装它,你不一定要使用JSON库,你可以直接打印JSON格式的文本,但它可以很容易地将perl对象转换为JSON prety。

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.

这篇关于如何从Perl CGI程序发送JSON响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆