gpt4 book ai didi

javascript - 如何从node js客户端调用node js函数

转载 作者:太空宇宙 更新时间:2023-11-04 03:27:06 25 4
gpt4 key购买 nike

我正在使用 html 模板,我注意到开发人员没有使用 RequireJS 或其他任何东西来要求和调用其他 Node 文件中的不同函数。相反,他们在 html 文件中使用它来初始化并调用该函数:

<script src="../../assets.js/test.js"></script>

<script type="text/javascript">
$(document).ready(function(){
test.initSomeFunction();
});
</script>

我在 assets/js/test.js 中有以下代码,它在 javascript 中定义了 initSomeFunction:

test = {
initSomeFunction: function() {
//Some code
}

initAnotherFunction: function() {
//More code
}
}

(如果有人能告诉我这个方法叫什么,这样我就可以进一步研究它,这将会很有帮助。)

当我尝试在主目录 /main.js 的 Node 应用程序中执行相同的操作时,就会出现问题。 Node 应用程序本身工作正常,但是当我添加如下内容时:

test2 = {
initMyFunction: function() {
console.log("I finally decided to work! Good luck...");
}
}

并像这样修改我的html文件:

<script src="../../main.js"></script>

<script type="text/javascript">
$(document).ready(function(){
test.initSomeFunction();
test2.initMyFunction();

});
</script>

那么就不行了。有人可以指出我正确的方向吗,因为我什至不知道要谷歌什么。我试图避免使用 RequireJS 或其他任何东西,因为我是一个完全的初学者,并且开发人员使用的方法听起来如此简单和诱人。

最佳答案

希望这个答案对您有帮助:

我使用的是 express ,所以我这样做是为了解决您的问题!

ma​​in.js文件的位置:

enter image description here

修改app.js添加:

      app.use(express.static(path.join(__dirname, '/')));

然后,在 View 文件中:

         <html>
<head>
<script src="public/javascripts/jquery-1.10.2.min.js"> </script>
<script src="main.js"></script>
</head>
<body>


<script>
$(function () {
//test.initSomeFunction();
test2.initMyFunction();

})
</script>
</body>
</html>

打开 Chrome 开发者工具。您将看到结果。

enter image description here

关于javascript - 如何从node js客户端调用node js函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43173198/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com