我怎样才能通过AJAX JavaScript数组Perl脚本? [英] How can I pass a JavaScript array through AJAX to a Perl script?
问题描述
我怎样才能创建一个通过AJAX通过JavaScript数组一个Perl数组?
How can I create a Perl array from a JavaScript array that is passed via AJAX?
的Perl访问:
@searchType = $cgi->param('searchType');
print @searchType[0];
输出:
employee,admin,users,accounts
看来,Perl的阵列设置的第一个值( @searchType [0]
)为所有通过JavaScript数组对象的字符串。
It seems that the Perl array sets the first value (@searchType[0]
) as a string of all the passed JavaScript array objects.
推荐答案
这是一个老问题,所以我不知道这是否仍是有趣的你,但是也许别人很关心这个问题了。
It is an old question, so I am not sure whether that is still interesting for you but maybe someone else is interested in this question, too.
正如上述评论已经建议,一个办法,通过AJAX传送一个javascript的数组,Perl是这个数组首先转换为一个JSON对象 - 使用JSON.stringify(jsArray); - 这是再德codeD中的Perl脚本。我加了下面,你的数组的第一个项目是通过警报返回一个很简单的例子。
As already suggested in the comments above, one way to pass a javascript array to Perl via ajax is to convert this array first to an JSON object - using "JSON.stringify(jsArray);" - which is then decoded in the Perl script. I added a very simple example below where the first item of your array is returned through an alert.
index.html的:
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
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";
这篇关于我怎样才能通过AJAX JavaScript数组Perl脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!