【发布时间】:2011-06-23 11:34:32
【问题描述】:
当我这样做时
$.each(result, function(i, n){
alert("key: " + i + ", Value: " + n );
});
然后对于我看到的每次迭代
key: 276, Value: {"owners":["he"],"users":["he","m"],"end":"07/06-2011","groups":[],"type":"in"}
如何在每次迭代中访问 owners、users、end、groups 和 type 的值?
在 Perl 中我会这样做
foreach my $key (keys %result) {
print $result{$key}{owners};
print $result{$key}{users};
...
}
更新
我从 JSON 中得到 result,就像这样
$.ajax({
type: "GET",
url: "/cgi-bin/ajax.pl",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { "cwis" : id },
// ...
success: function(result){
if (result.error) {
alert('result.error: ' + result.error);
} else {
$.each(result, function(i, n){
alert( "key: " + i + ", Value: " + n );
});
}
}
});
更新 2
问题似乎是服务器端没有发送探测器 JSON。
这是生成 JSON 字符串的服务器端脚本。
!/usr/bin/perl -T
use CGI;
use CGI::Carp qw(fatalsToBrowser);
use CGI qw(:standard);
use JSON;
use utf8;
use strict;
use warnings;
my $cgi = CGI->new;
$cgi->charset('UTF-8');
my $json_string = qq{{"error" : "The user do not have any activities."}};
my $json = JSON->new->allow_nonref;
$json = $json->utf8;
# @a and $act is now available
my $data;
foreach my $id (@a) {
$data->{$id} = $json->encode(\%{$act->{$id}});
}
$json_string = to_json($data);
print $cgi->header(-type => "application/json", -charset => "utf-8");
print $json_string;
【问题讨论】:
-
能不能也显示一下perl脚本生成的结果?
-
我不是 CGI 专家,但看起来您正在将数据双重编码为 JSON。一次使用
my $json = JSON->new->allow_nonref; $json = $json->utf8;,然后再次使用$data->{$id} = $json->encode(\%{$act->{$id}})。不能说我以前曾尝试过这样做! -
@T9b :你完全正确!那就是问题=)如果您发布是作为解决方案,那么我接受它=)非常感谢=)
-
@ Sandra Schlichting - 我将在下面更新我的答案。
标签: javascript jquery perl