2017-01-23 49 views
4

我正在開發一個Catalyst數據庫項目,並嘗試通過jQuery執行一些AJAX請求。參數是否正發送行,如在圖像中可以看出1.從AJAX請求遍歷Perl數組

List of parameters and values received in AJAX request

注意兩個「診斷」和「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)調試打印以下:

Debugs of array iteration

這是否表明我的「數組」只是一個帶有字符串的單維變量?我試圖分裂它,但那也行不通。

回答

1

您可以存儲在散列中的唯一值是標量。因此,$params->{type_consent}是一個標量,而不是一個列表。但是,由於對事物(標量,數組,哈希,對象,球體等)的引用也是標量,因此可以將引用存儲在散列中。

因此,$params->{type_consent}是對數組的引用,而不是數組或列表本身。

我想你想的話,要麼是賦值給my $type_consent = $params->{type_consent};然後用@$type_consent爲您的數組(因此它們都指向同一陣列 - 通過@$type_consent改變的東西改變%$params該數組),複製數組說my @type_consent = @{$params->{type_consent}};

哪一個我選擇使用情景式,但我傾向於參考選項,如果只是爲了保持內存使用率下降,如果沒有理由複製它。

+0

兩個都很好。非常感謝,@Tanktalus。我個人認爲第二個選項有點容易閱讀,所以我要去那個,但都工作:) –

+0

我正在做一些測試,它似乎像這個工作正常,只有當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}};' 任何想法? –

+1

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