Reputation: 55
I want to access a JSON array inside the script tag of a EJS file. I'm passing the JSON array from my index.js file to the EJS file while rendering it. The code is:
sampleJArr=["data1","data2","data3"];
app.get('/test', function(req,res){
res.render('testfile',{
'mJsonArr': sampleJArr
});
In the EJS file (testfile.ejs), code-:
<div>
<!--Printing the JSON array. It prints -->
<p>JSON.stringify(mJsonArr)</p>
<button onClick="myFunc">Take test</button>
</div>
<script>
function myFunc(){
var JsonData= <%= mJsonArr[0] %>
console.log(JsonData)
}
</script>
Error:-Uncaught ReferenceError: myFunc is not defined at HTMLButtonElement.onclick
But when I'm trying to do a console("some string") inside myFunc then it's not giving that error. Only when I'm accessing mJsonArr inside the script tag, I'm getting UncaughtRefrence error. How can I access the passed mJsonArr inside my script tag ? Please contribute. Thankyou.
Upvotes: 0
Views: 1787
Reputation: 2264
The reason why you can not access mJsonArr[0] in your script tag is because EJS just replace <%= mJsonArr[0] %>
to data1
which means your generated html will be like
<div>
<!--Printing the JSON array. It prints -->
<p>JSON.stringify(mJsonArr)</p>
<button onClick="myFunc">Take test</button>
</div>
<script>
function myFunc(){
var JsonData= data1
console.log(JsonData)
}
</script>
In which there are 2 points are wrong
This need to be changed to onClick="myFunc()". Otherwise it will never invoke.
This is not assigning a string value 'data1' to variable. It is assigning a value of a variable named 'data1' to variable JsonData.
The correct way to do this should be
<div>
<!--Printing the JSON array. It prints -->
<p>JSON.stringify(mJsonArr)</p>
<button onClick="myFunc()">Take test</button>
</div>
<script>
function myFunc(){
var JsonData= '<%= mJsonArr[0] %>'
console.log(JsonData)
}
</script>
Hope it can help you
Upvotes: 1