ASP array to JavaScript array

2019-07-04 03:59发布

问题:

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?

回答1:

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>


回答2:

That won't work, because the asp code is going to be executed before the javascript, so there is no way to pass n in. If you really need asp to be doing some heavy lifting for you, you can make an ajax call or piggy back on a pre-established socket connection.



回答3:

I realise this one has been answered, but perhaps an easier rendition of this would be simply...

var jsArray = <%= "[" & Join(tulemused, ",") & "]" %>;

If you're using strings, then obviously put the speech marks in, like so...

var jsArray = <%= "['" & Join(tulemused, "','") & "']" %>;

This will avoid any embarrassing use of loops when they're not necessary.

NOTE

Please note I made a slight typo with this earlier and included square brackets inside the Join statement. This was incorrect, and the current should be used in preference.



回答4:

I this this has to work for u

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

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