How to pass a JavaScript array via AJAX to a Perl script?

How to create a Perl array from a JavaScript array that is passed through AJAX?

Access to Perl:

@searchType = $cgi->param('searchType');
print @searchType[0];

Output:

employee,admin,users,accounts

It seems that the Perl array sets the first value ( @searchType[0]) as a string of all the passed objects in the JavaScript array.

+2
source share
2 answers

This is an old question, so I'm not sure if this is interesting for you, but maybe someone else is interested in this question.

, javascript Perl ajax - JSON - "JSON.stringify(jsArray)"; - Perl script. , .

index.html

<!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(){
                    var jsArray = ["employee", "admin", "users", "accounts"];
                    var jsArrayJson = JSON.stringify(jsArray);
                    $.ajax({
                            type: 'POST',
                            url: '/cgi-bin/ajax/stackCGI/processJsArray.pl', //change the path
                            data: { 'searchType': jsArrayJson},
                            success: function(res) {alert(res);},
                            error: function() {alert("did not work");}
                    });
                })

            })

        </script>
    </head>
    <body>
       <button id="test" >Push</button>

    </body>
</html>

processJsArray.pl

#!/usr/bin/perl

use strict;
use warnings;

use CGI;
use JSON;

my $q = CGI->new;

my @myJsArray = @{decode_json($q->param('searchType'))}; #read the json object in as an array

print $q->header('text/plain;charset=UTF-8'); 
print "first item:"."\n";
print $myJsArray[0]."\n";
+3

key=value&key=other-value.

var searchType = ["employee", "admin", "users", "accounts"];
var keyName = "searchType";
for (var i = 0; i < searchType.length; i++) {
    searchType[i] = encodeURIComponent(keyName) + "=" + encodeURIComponent(searchType[i]);
}
var queryString = searchType.join("&");

queryString URL- .

+1