简体   繁体   中英

iterate dynamic array in perl cgi script

I pass via jquery

$.ajax({
    'type' : 'POST',
    'data' : { 
               'foo': {
                   'foo1':'bar1,
                   'foo2':'bar2'
               }
            },
    'async' : false,
    'global' : false,
    'url' : "path/to/script.pl",
    'dataType' : "json",
    'success' : function(data) {
        json = data;
    },
    'error' : function(jqxhr, textStatus, error) {
        console.log("Request Failed: " + textStatus);
        console.log(error);
    }
});

to my cgi script.

HTML Parameter: foo%5Bfoo1%5D=bar1&foo%5Bfoo2%5D=bar2

I can't use foo as an array by using $cgi->param('foo[]')

CGI::param called in list context from package main line 30, this can lead to vulnerabilities. See the warning in "Fetching the value or values of a single named parameter

i seems that all array elements are hardcoded into parameter like 'foo[foo1]'.

is it possible to get dynamic access?

Output of use Data::Dumper; print Dumper scalar $cgi->Vars(); use Data::Dumper; print Dumper scalar $cgi->Vars();

$VAR1 = bless( {
                 'use_tempfile' => 1,
                 '.fieldnames' => {},
                 '.charset' => 'ISO-8859-1',
                 '.parameters' => [
                                    'foo[foo1]',
                                    'foo[foo2]'
                                  ],
                 'escape' => 1,
                 'param' => {
                              'foo[foo2]' => [
                                               'bar2'
                                             ],
                              'foo[foo1]' => [
                                               'bar¹'
                                             ]
                            }
               }, 'CGI' );

You have to send data as json string

    'data' : JSON.stringify({
               'foo': {
                   'foo1':'bar1',
                   'foo2':'bar2'
               }
            }),

and at the server side convert string to native perl structure,

use JSON;
my $data = decode_json( $cgi->param('keywords') );

I guess you want something like this.First the jquery which sends the data.

<!DOCTYPE html>
<html>
    <head>
        <title>Testing ajax</title> 
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


    <script>

            $(document).ready(function() {

                $("#test").click(function(){
                    $.ajax({
                            type: 'POST',
                            url: 'ajax1.cgi',
                            data: {'foo': { 
                                            'foo1':'bar1', 
                                            'foo2':'bar2'
                                 }
                                 },
                            success: function(res) {

                                                        $( ".demo" ).append("your first var is: " + res.foo1+"<br />");
                                                        $( ".demo" ).append("your second var is  :"+res.foo2);

                                                    },
                            error: function() {alert("did not work");}
                    });
                })

            })



        </script>
    </head>
    <body>

        <button id="test" >Testing</button>
        <div class="demo" >
        </div>
    </body>

The cgi script is ajax1.cgi. Note that the response is sent in json format.

#!/usr/bin/perl

use strict;
use warnings;

use JSON; #if not already installed, just run "cpan JSON"
use CGI;
use Data::Dumper; 


my $cgi = CGI->new;

print $cgi->header('application/json;charset=UTF-8');

#my $id = $cgi->param('foo[]');
my @cgivars=$cgi->param; #get all key value of param in array
my $cgivar1="Not defined";
my $cgivar2="Not defined";
foreach my $a(@cgivars){
 if($cgi->param($a) eq 'bar1'){
       $cgivar1="bar1"; #means do whatever you like to do here
       }
else{
       $cgivar2="bar2"; #same here etc
}
}
#print Dumper scalar $cgi->Vars();
#convert  data to JSON
my $op = JSON -> new -> utf8 -> pretty(1);
my $json = $op -> encode({
    foo1=>$cgivar1,
    foo2=>$cgivar2
});
print $json;

I was looking for a perl-own method to convert json "arrays" back to real arrays or hash.

So I did it by my own:

my $cgi = CGI->new();    
my %hash = ();

foreach my $a ($cgi->param())
{
    if($a =~ /^([\w\-]+)\[(.*)\]/)  #TODO multidimensional
    {
        $hash{$1}{$2} = $cgi->param($a);
    }
    else
    {
        $hash{$a} = $cgi->param($a);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM