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
誰かがこれを理解するのを手伝ってくれませんか。ありがとうございました。