javascript - 从 html 页面执行 Nodejs 脚本?

标签 javascript node.js coffeescript express

我目前正在使用 Express.js创建我的网站。 我的主服务器脚本称为index.coffee。我还创建了一个名为 request.js 的脚本,它发出 GET 请求并显示响应

  console.log(list);

从控制台运行脚本时没有问题:node request.js

我的问题是:如何通过在同一页面上显示列表来使页面上的“获取此列表”按钮响应单击(即,执行 request.js on服务器并显示结果)?

app.js

/**
 * Module dependencies.
 */

var express = require('express')
  , routes = require('./routes');

var app = module.exports = express.createServer();

// Configuration

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set ('view engine', 'coffee');
app.register('.coffee', require('coffeekup').adapters.express);

  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
  app.use(express.errorHandler());
});

app.get('/', function(req, res) {
  res.render('index',{ layout: false });
});



app.listen(3000);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);

index.coffee

doctype 5
html ->

  head ->
    body

p -> “嘿”

最佳答案

我使用纯 JS 而不是 CoffeeScript ,所以这里是 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 文件,并将其保存在 Node 应用程序目录的 /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

关于javascript - 从 html 页面执行 Nodejs 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9670222/

相关文章:

javascript - 使用 `node` 启动 Node 应用程序可以工作,但使用 `/usr/bin/node` 启动它时则不行

javascript - 根据机器类型或 IDE 标志配置 Node.js 应用程序

javascript - Backbone Model 有条件地触发事件,View 听不到它

jquery - 滚动时更改 View 中特定 div 的背景颜色的最佳方法是什么?

javascript - 多次运行 grunt 任务直到失败

javascript - 如何使用 Babel 和 ES6 正确地子类化 Promises

php - 将输出的 Html 按钮与输出的 Php/MySQL 数据匹配

javascript - Node : adding a string as a file into a tar archive (without temporary files)

javascript - Bootstrap 按钮 onclick 不起作用

javascript - 使用 React 以类似于 Markdown 的方式向用户评论添加功能