简体   繁体   English

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

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

I am writing a JSON response from a perl/cgi program. 我正在编写一个来自perl / cgi程序的JSON响应。 The header's content type needs to be "application/json". 标题的内容类型必须是“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. 我将使用jQuery的JSON库捕获响应。 Where am I missing in sending the JSON response. 我在发送JSON响应时遗漏了哪里。

I am doing this in a perl/cgi program. 我在perl / cgi程序中这样做。

I use these in the top of my code: 我在我的代码顶部使用这些:

use CGI qw(:standard);
use JSON;

Then I print the json header: 然后我打印json标题:

print header('application/json');

which is a content type of: 这是一种内容类型:

Content-Type: application/json

And then I print out the JSON like this: 然后我打印出这样的JSON:

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

My javascript call/handles it like this: 我的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() {
        }
    });

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

Here is how to generate the request in Mason , the web framework for Perl. 以下是如何在Mason (Perl的Web框架)中生成请求。

Mason is analogous to Pylons or Ruby On Rails. 梅森类似于Pylons或Ruby On Rails。

<%init>

use JSON;

my %hash = { a => 'a', b => 'b' };
my @list = ( 1, 2, \%hash );

# Mason object $r for Apache requests, automatically sets the header
$r->content_type('application/json');

# Pass a reference to anything (list, hash, scalar) for JSON to encode
my $json = new JSON;
print $json->encode(\@list);

</%init>

And then handle it in Prototype , the JavaScript web abstration: 然后在Prototype中处理它,JavaScript web abstration:

var req = new Ajax.Request('request.html', {
    method: 'get',
    parameters: {
        whatever: 'whatever'
    },
    onCreate: function() {
        // Whatever
    },
    onSuccess: function(response) {
        // This only works if you set the 'application/json' header properly
        var json = response.responseJSON;

        // Since you sent a list as the top-level thing in the JSON,
        // then iterate through each item
        json.each(function(item) {
            if (item instanceof Object) {
                item = new Hash(item);
            } else if (item instanceof Array) {
                // Do array stuff
            } else {
                // Do scalar stuff
            }
        });
    },
    onFailure: function() {
        // Failed
    }
});

Even if you specify the type "application/json" you still need to parse the text. 即使您指定类型“application / json”,您仍然需要解析文本。 jQuery do this for you, using the $.getJSON function,ie: jQuery使用$ .getJSON函数为您执行此操作,即:

$.getJSON("http://someurl.com/blabla.json",{some: "info"},function(json){
  alert(json["aKey"]["anotherOne"]);
});

(here the specs ). (这里是规格 )。

But maybe you are already aware of this, so the problem resides somewhere else: can you please tell us a sample of your json response, because maybe the problem is that is not valid. 但也许你已经意识到了这一点,所以问题存在于其他地方:你能告诉我们你的json响应的样本,因为问题可能是无效的。 It's not really clear to me why you say that "doesnt seems to be recognised": when I write json services the first test I do is to call them on the browser and maybe fire up firebug and try to parse it (so yes the response it's a text response, but javascript it's still quite happy to parse it and return a json object). 我不清楚为什么你说“似乎没有得到认可”:当我写json服务时,我做的第一个测试是在浏览器上调用它们并且可能启动firebug并试图解析它(所以是的回复这是一个文本响应,但是javascript仍然很乐意解析它并返回一个json对象)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM