您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

从HTML页面执行Nodejs脚本?

从HTML页面执行Nodejs脚本?

我使用普通的JS而非咖啡脚本,因此这是每个Fosco注释(称为server.js)的示例:

var express = require('express'),
    list = require('./request.js').Request; // see  template

var app = express.createServer();

app.use(express.static(__dirname + '/public')); // exposes index.html, per below

app.get('/request', function(req, res){
    // run your request.js script
    // when index.html makes the ajax call to www.yoursite.com/request, this runs
    // you can also require your request.js as a module (above) and call on that:
    res.send(list.getList()); // try res.json() if getList() returns an object or array
});

app.listen(80);

编写index.html文件,然后将其保存在/public节点应用目录的子文件夹中(通过暴露在上方express.static)。:

<html>
    <body>
    <div id="button">Get this List</div>
    <div id="response"></div>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
        $('#button').click(function() {
            // run an AJAX get request to the route you setup above...
            // respect the cross-domain policy by using the same domain
            // you used to access your index.html file!
            $.get('http://www.yoursite.com/request', function(list) {
                $('#response').html(list); // show the list
            });
        });
    });
    </script>
    </body
</html>

如果将 request.js 作为模块包含在内,则可能如下所示:

var RequestClass = function() {
    // run code here, or...
};

// ...add a method, which we do in this example:
RequestClass.prototype.getList = function() {
    return "My List";
};

// Now expose with module.exports:
exports.Request = RequestClass;

node server.js在您的服务器上运行。然后前往www.yoursite.com/index.html

Node 2022/1/1 18:21:20 有456人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶