从AJAX请求遍历Perl数组
我正在开发一个Catalyst数据库项目,并尝试通过jQuery执行一些AJAX请求。参数是否正发送行,如在图像中可以看出1.从AJAX请求遍历Perl数组
注意两个“诊断”和“type_consents”(和其相应的日期)作为值的阵列(发送值1,值2,...值n)。
现在对于服务器端处理,Catalyst::Request
允许通过$req->parameters
进行简单的数据检索,但它似乎不适用于我。
我做这样的:
my $params = $c->request->parameters; #Retrieving all parameters
my @type_consents = $params->{type_consent};
my @date_consents = $params->{date_consent};
my @diagnosis = $params->{diagnosis};
my @date_diagnosis = $params->{date_diagnosis};
然后我需要循环这些阵列,并插入每对值(diagnosis|date , consent|date)
的。另外,我需要存储和处理所有事务,并在eval()
块执行一次全部,所以我在做这样的:
my %transactions;
# Diagnosis
my $diag_index = 0;
foreach my $key (0 .. $#diagnosis) {
$transactions{diagnosis}{$diag_index} = $diagnosis_mod->new(
{
subject_id => $subject_id,
diagnosis_date => $date_diagnosis[$key],
diagnosis => $diagnosis[$key],
diagnosis_comment => "",
suggested_treatment => ""
}
);
print STDERR "\n" . $date_diagnosis[$diag_index];
print STDERR "\n DEBUG: $date_diagnosis[$diag_index] | $diagnosis[$diag_index] | key: $diag_index";
print STDERR "\n DEBUG2:" . Dumper(@date_diagnosis) . " | " . Dumper(@diagnosis);
$diag_index++;
}
# I'm avoiding evaluating and performing the transactions so neither eval() nor database impact are shown above.
那些(1)调试打印以下:
这是否表明我的“数组”只是一个带有字符串的单维变量?我试图分裂它,但那也行不通。
您可以存储在散列中的唯一值是标量。因此,$params->{type_consent}
是一个标量,而不是一个列表。但是,由于对事物(标量,数组,哈希,对象,球体等)的引用也是标量,因此可以将引用存储在散列中。
因此,$params->{type_consent}
是对数组的引用,而不是数组或列表本身。
我想你想的话,要么是赋值给my $type_consent = $params->{type_consent};
然后用@$type_consent
为您的数组(因此它们都指向同一阵列 - 通过@$type_consent
改变的东西改变%$params
该数组),或复制数组说my @type_consent = @{$params->{type_consent}};
。
哪一个我选择使用情景式,但我倾向于参考选项,如果只是为了保持内存使用率下降,如果没有理由复制它。
两个都很好。非常感谢,@Tanktalus。我个人认为第二个选项有点容易阅读,所以我要去那个,但都工作:) –
我正在做一些测试,它似乎像这个工作正常,只有当2个或更多的元素被发送。 无论何时发送1个元素(最低可接受的请求),我都会收到此错误: '[error]捕获的pbitdb :: Controller :: Subjects-> add中的异常无法使用字符串(“1”)作为ARRAY ref,同时在/home/lioneluranl/svn/pbitdb/pbitdb/script/../lib/pbitdb/Controller/Subjects.pm 119行使用“strict refs”。“ ......在这种情况下, 1“是发送的值...并且引用的行是我声明列表的那一行: 'my @type_consents = @ {$ params - > {type_consent}};' 任何想法? –
IMO,它是可怜的设计有动态类型 - 一个关键,可以有一个标量值*或*一个数组(参考)值。但是,如果您调用的API不受您的控制,您可能需要在代码中处理它:'my @type_consent = ref $ params - > {type_consent}? @ {$ params - > {type_consent}}:$ params - > {type_consent};'类似于保持引用:'my $ tc = ref $ params - > {type_consent}? $ params - > {type_consent}:[$ params - > {type_consent}]' – Tanktalus