英文:
Calling user defined JavaScript function inside ejs file
问题
I wrote my own JavaScript function inside an ejs file which I want to use it inside that file. The problem is that it is not working because the function is declared to be undefined.
I have declared that function inside the ejs file as illustrated below.
//my ejs file
<script>
function c_tab (){
//codes...
return "data";
}
</script>
</head>
<body>
<h1>WELCOME TO E J S </h1>
<p>Ok this willrecievedata from server ... <%= c_tab(); %>
</p>
The error report says that c_tab is not defined
So how to use a user-defined JavaScript function inside an ejs file.
英文:
I wrote my own JavaScript function inside an ejs file which I want to use it inside that file. The problem is that it is not working because the function is declared to be undefined .
I have declared that function inside the ejs file as illustrated below.
//my ejs file
<script>
function c_tab (){
//codes...
return "data";
}
</script>
</head>
<body>
<h1>WELCOME TO E J S </h1>
<p>Ok this willrecievedata from server ... <%= c_tab(); %>
</p>
The error report says that c_tab is not defined
So how to use a user defined javascript function inside ejs file .
答案1
得分: 1
以下是翻译好的部分:
好的,对于你的问题,基本答案可能是:
<%
var foo = function(){return 'bar'};
%>
<body>
<h1>欢迎来到 EJS </h1>
<p>好的,这将从服务器接收数据... <%= foo(); %>
</p>
</body>
但是,由于你在代码中提到了“从服务器接收数据”,我假设你是通过 .render()
从 Express 传递本地变量到 EJS。
在这种情况下,这些变量应该只是“可用的”,但你想要它们在客户端代码中可用。尝试类似以下的方法:
<script>
var foo = <%= JSON.stringify(bar_obj_from_server)%>
var fooString = ''<%= bar_str_from_server %>'';
</script>
英文:
Well, the basic answer to your question is probably
<%
var foo = function(){return 'bar'};
%>
<body>
<h1>WELCOME TO E J S </h1>
<p>Ok this will recieve data from server ... <%= foo(); %>
</p>
</body>
but since you said "receive data from the server" in your code, I presume you are passing local variables from express to ejs via .render()
In that case the variables should just be available, but you want them available in your client side code. Try something like
<script>
var foo = <%= JSON.stringify(bar_obj_from_server)%>
var fooString = '<%= bar_str_from_server %>'
<script>
答案2
得分: 0
使用Scriptlet标签而不是script标签:
<%
function c_tab (){
//codes...
return "data";
}
%>
英文:
Use Scriptlet tag instead of script tag:
<%
function c_tab (){
//codes...
return "data";
}
%>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论