質問

I am passing an array via ejs with JavaScript. I can get to the values inside ejs but not from JavaScript. Below is more information.

node.js

FileTypes = {"application/octet-stream":20,
                 "audio/mpeg":12,
                 "text/html" :71}
res.render('index.ejs', {FileTypes: JSON.stringify(FileTypes)});

index.ejs

 <script type="text/javascript">

   var FileTypes =  <%=FileTypes%>;
   //Error message on the console - Uncaught SyntaxError: Unexpected token & 

 </script>

Any ideas?

役に立ちましたか?

解決

Using the <%= %> tag in EJS will escape the output, so {"application/octet-stream": ... } is being turned into {&quot;application/octet-stream&quot;: ... }, resulting in JavaScript like this:

<script type="text/javascript">                                                                                                                                          
  var FileTypes = {&quot;application/octet-stream&quot;:20,&quot;audio/mpeg&quot;:12,&quot;text/html&quot;:71};
</script>

So, you can see where the "Unexpected token &" is coming from. The solution is to use the <%- %> tag, which won't escape the output:

<script type="text/javascript">
  var FileTypes = <%- FileTypes %>;
  //      here -----^
</script>

...and will give you what you want:

<script type="text/javascript">                                                                                                                                          
  var FileTypes = {"application/octet-stream":20,"audio/mpeg":12,"text/html":71};
</script>             
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top