[英]How to print only the `this` object's name , and not it's contents in javascript?
[英]How to access an object's contents in 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;
在$.each
回調中, this
指向當前元素,因此
$.each(result, function(i, n){
alert(this.users);
});
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}})。
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 );
});
});
您可以像這樣訪問它們:
n.owners
要么
n['owners']
或者您可以使用另一個周期:
$.each(result, function(i, n){
if (typeof(n)=='object') {
$.each(n, function(k, v){
alert('n.'+k+' = ' + v);
});
}
});
編輯: jsFiddle示例 示例2
edit2:為避免變得undefined
簡單檢查鍵i
是否等於"Value"
,因此其value將是一個對象
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.