How to access an object's contents in javascript?
When I do
$.each(result, function(i, n){
alert("key: " + i + ", Value: " + n );
});
then for each iteration I see
key: 276, Value: {"owners":["he"],"users":["he","m"],"end":"07/06-2011","groups":[],"type":"in"}
How do I access the value开发者_如何转开发s of owners
, users
, end
, groups
, and type
for each iteration?
In Perl would I have done
foreach my $key (keys %result) {
print $result{$key}{owners};
print $result{$key}{users};
...
}
Update
I get result
from JSON like so
$.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 );
});
}
}
});
Update 2
It seams that the problem is the server side is not sending prober JSON.
This is the server side script that generate the JSON string.
!/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);
UPDATE:
Apparently my comment on the question was the answer:
I'm no CGI expert but it looks like you are double encoding your data into JSON. Once with
my $json = JSON->new->allow_nonref; $json = $json->utf8;
and then again with
$data->{$id} = $json->encode(\%{$act->{$id}}) .
in $.each
callbacks, this
points to the current element, so
$.each(result, function(i, n){
alert(this.users);
});
n.owners or n['owners']
n.users or n['users']
etc.
In a loop...
$.each(result, function(k,v) {
console.log("key: " + k + ", value: " + v );
$.each(v, function(k,v)) {
console.log("key: " + k + ", value: " + v );
});
});
you can access them like this:
n.owners
or
n['owners']
or you can use another cycle :
$.each(result, function(i, n){
if (typeof(n)=='object') {
$.each(n, function(k, v){
alert('n.'+k+' = ' + v);
});
}
});
edit: jsFiddle Example Example 2
edit2: to avoid getting undefined
make a simple check whether the key i
is equal to "Value"
, so it's value will be an object
精彩评论