Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

passing an array from EJS to Javascript

I am trying to passe an array from ejs to JavaScript. I can get to the values inside ejs but not from JavaScript. all the time i get undefined because the contents of the variable "test" is a string is not an array.

<script>

var test = '<%- level_tab %>';
alert(test);

function level(s1,s2){
            var s1 = document.getElementById(s1);
            var s2 = document.getElementById(s2);
            s2.innerHTML = "";
            if(s1.value == "level_0"){
                var optionArray = test;
            }
            else if(s1.value == "level_1"){
                var optionArray = ["test|test01", "test0|test02"];
            }
 for(var option in optionArray){
                var pair = optionArray[option].split("|");
                var newOption = document.createElement("option");
                newOption.value = pair[0];
                newOption.innerHTML = pair[1];
                s2.options.add(newOption);
            }
        }
</script>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have to stringify the array

var test = <%- JSON.stringify(level_tab) %>;

I'm not familiar with EJS but in general the same principle should apply even if syntax is slightly different in EJS.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...