![](/img/trans.png)
[英]Read variable from app.js in index.html file in a website Bluemix application
[英]How to call a function from index.html to app.js file in node js application javascript
我有一个节点js应用程序,其中有我的app.js和一个显示为/ index的html文件。现在在索引文件中,我有一个按钮和文本框,当我单击按钮时,我试图调用一个函数。在该函数中,我将有一个带有一些文本“ Hello”的变量,该变量应显示在文本框中。我无法实现这一点可以有所帮助。
<html>
<body>
<div class="jumbotron" style="padding:40px;">
<h1>Hello!!!</h1>
<div>
<button type="submit" onclick="getData();">Call</button>
<input type="text">
</div>
</div>
</div>
</body>
</html>
app.js
app.get('/index',function(req,res){
res.sendFile(path.join(__dirname+'/index.html'));
});
function getData(){
console.log("Hello");
var text="Hello";
};
目前我正在获取未定义getData的参考错误。有人可以在这里提供帮助。
index.html在浏览器中运行,因此您无法在app.js
服务器端调用getData()
函数
按照Nenad Vracar的建议将getData()
函数主体移至index.html
或使用某种API进行客户端-服务器通信。
代码移到index.html
<html>
<body>
<script>
function getData() {
var text="Hello";
document.querySelector('#input_id').value = text;
}
</script>
<div class="jumbotron" style="padding:40px;">
<h1>Hello!!!</h1>
<div>
<button type="submit" onclick="getData();">Call</button>
<input type="text" id="input_id">
</div>
</div>
</div>
</body>
</html>
我认为您可能误解了NodeJS是什么。 Node与在浏览器中运行的其他JavaScript或jQuery不同。
节点是在服务器上运行的代码。 您在app.js
正确完成的工作是让服务器将index.html
文件发送到浏览器。 但是在那之后,浏览器所知道并有权访问的全部是index.html
文件,它是一个单独的文件和上下文,因此不再具有对服务器的访问权。
使页面在服务器上调用函数的唯一方法是创建某种API,其中页面将单独的http请求发送到服务器,然后服务器以函数的输出作为响应。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.