Accessing Perl Array in JavaScript

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-20 07:23:12

问题


I have an array of unknown size in perl generated by some other perl module. Now, precisely I want to find if a value passed to a jquery function exists in the perl array or not.

Is there a way I can do an element by element comparison of the input value against each value in perl array?

I looked around and looks like I can access perl array in jquery by providing the index but we don't know the size of the array. So I don't know when to stop.

My mason code looks something similar to:

<%perl>
    my @testArray = [call to some other perl module to get the values]
</%perl>

<script type="text/javascript">
    function checkIfValExistsInTestArray(val) {
        // Code to test if "val" exists in "@testArray". Returns boolean true/false.
    }
</script>

回答1:


To check for existence, you'd want a hash. A simple way of transmitting the data would be to encode it using JSON.

% use JSON qw( );

<script type="text/javascript">

var testArray = <% JSON->new()->encode({ map { $_ => 1 } get_values() }) %>;

function checkIfValExistsInTestArray(val) {
   return testArray[val];
}

</script>

For example, if get_values() returned apple and orange, you'd get

<script type="text/javascript">

var testArray = {"apple":1,"orange":1};

function checkIfValExistsInTestArray(val) {
   return testArray[val];
}

</script>

I don't know Mason, so there could be errors, but you get the idea.



来源:https://stackoverflow.com/questions/24808800/accessing-perl-array-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!