0

jQuery、AJAX、JSON、および Perl を使用する小さなプロジェクトを行っています。バックエンドでは、Perl とその CGI モジュールを使用して JSON オブジェクトを返しています。

#!/usr/software/bin/perl5.8.8

use strict;
use warnings;
use CGI qw(:standard);
use JSON;

print header('application/json');
my $json;
# eventually the json that will be returned will based on params,
# for now using this list as example.
$json->{"entries"} = [qw(green blue yellow red pink)];
my $json_text = to_json($json);
print $json_text;

How can I send a JSON response from a Perl CGI program?の助けを借りて、上記のスクリプトを書くことができました。

このスクリプトは、jQuery の get を使用して呼び出されます。

jQuery.getJSON("script.pl?something=whatever", function(data, status) {
    console.log(data);
    console.log(status);
},"json").error(function(jqXhr, textStatus, error) {
    /* I am always ending up here. */
    console.log(jqXhr);
    console.log("ERROR: " + textStatus + ", " + error);
});

上記の jQuery 呼び出しから、JSON オブジェクトが返されることを期待していましたが、代わりに Perl スクリプト全体が返されました。コマンド ラインからスクリプトを実行すると、次のように返されるため、コンテンツ タイプが正しく設定されていることがわかります。

Content-Type: application/json

誰かがこれを理解するのを手伝ってくれませんか。ありがとうございました。

4

2 に答える 2

4

代わりに、Perl スクリプト全体を取得します

サーバーは Perl スクリプトを実行しておらず、プレーン テキストとして提供しています。

サーバーを CGI 用に構成する方法については、サーバーのマニュアルを読む必要があります。

于 2013-05-14T23:47:24.457 に答える
0

他の人が指摘したように、Perl スクリプトを CGI として実行するように Web サーバーを構成する必要があります。Web サーバーが Apache で、CGI の名前が「json.cgi」の場合、次のような行を httpd.conf に追加します。

AddHandler cgi-script .cgi

jQuery を使用しているため、to_json という見出しの下にある JSON ポッドからこの小さなナゲットを読み取る必要があります。

   If you want to write a modern perl code which communicates to outer
   world, you should use "encode_json" (supposed that JSON data are
   encoded in UTF-8).

残りの話では「perldoc JSON」を使用してください。

于 2013-05-15T04:47:33.860 に答える