Search code examples
javascriptarraysasp-classic

ASP array to JavaScript array


Here's my problem:

I have a one-dimensional array that is a result of some server side code in the same .asp. I want to take this array and transfer the strings in it to a javascript array, so I can use the values in a table for displaying purposes.

This is the code I have tried:

<script language="javascript">
var jsArray = [];
var n = <%=r%>;

for (n = 0; n < 4; n++){
    jsArray[n] = '<%=tulemused(n)%>'; //this isn't working for some reason
}

</script>

I personally think the error is created by the n variable. It is displayed correctly when I write it in a paragraph, but it doesn't work when used in the line marked above. I have also considered that the for loop could be the problem.

What am I doing wrong?


Solution

  • Your "<% ="-like code will be executed when the page is rendered. That means, the way it is written, that code will be executed once when the page is rendered, trying to access the n-th element of the array. However, the variable n would NOT be in the scope of access at that time.

    Hence, if you wish you use such code, you need to include the iteration also in the embedded code.

    An easier workaround would be to store the list of strings (that you wish to pass) as a single concatenated string, separated by a known delimiter and access the concatenated string in Javascript and split it in JS.

    That is, if the string variable tulemused_concatenated holds the concatenated strings, separated by the delimiter ',', the following script should work.

    <script language="javascript">
    var jsArray = [];
    var n = <%=r%>;
    
    var concatenated_string = '<%=tulemused_concatenated%>'; //this isn't working for some reason
    var jsArray[n] = concatenated_string.split(',');
    
    </script>