如何在javascript中访问对象的内容?
当我做
$.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;
document.write(result[key].owners);
document.write(result[key].users);
更新:
显然,我对这个问题的评论是这样回答的:
我不是CGI专家,但它看起来像是将数据双重编码为JSON。 一次
my $json = JSON->new->allow_nonref; $json = $json->utf8;
然后再一次
$ data - > {$ id} = $ json-> encode(%{$ act - > {$ id}})。
在$.each
回调中, this
指向当前元素,所以
$.each(result, function(i, n){
alert(this.users);
});
n.owners or n['owners']
n.users or n['users']
etc.
在循环中...
$.each(result, function(k,v) {
console.log("key: " + k + ", value: " + v );
$.each(v, function(k,v)) {
console.log("key: " + k + ", value: " + v );
});
});
链接地址: http://www.djcxy.com/p/46103.html
上一篇: How to access an object's contents in javascript?
下一篇: jquery + IE 7 & 8