从 HTML 页面执行 Node.js 脚本?

21

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

  console.log(list);

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

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

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 -> "嗨"


1
你应该创建一个请求处理程序(就像你为索引页面所做的那样),它执行request.js中的代码... 你可以使用Ajax调用来获取这些数据并将其加载到页面中。 - Fosco
你有关于请求处理程序和使用 Ajax 方式获取数据的教程吗?我对 Node 和 Ajax 都很陌生,谢谢你的回答! - Louis
你应该按照现在的状态发布你的代码。我不使用CoffeeScript,所以无法提供完整的解决方案,但肯定会有其他人能够帮助(如果代码在这里)。 - Fosco
我会去做,谢谢 :) (HTML的解决方案也可以) - Louis
1个回答

13

我使用的是纯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


1
好的,我尝试了(顺便说一下,我将<div id="button">替换为<button id="button">。。。(它只能工作1次,但没关系)。我对这一行很感兴趣:// you can also require your request.js as a module, and export a function from it,我该如何做到这一点?这很有趣,因为当我执行var list = require('request.js')时,它会显示没有POST方法。我如何避免这个错误? - Louis
我会更新我的答案,包括如何将request.js作为模块使用。我不确定为什么它会说你没有POST方法。我猜想你调用了list上未公开或未定义的方法。 - Wes Johnson
嘿,一切都正常工作,除了这个问题:当我尝试使用res.send("sent");时它可以工作,但是使用res.send(list.prototype.getList());时就不行了。我认为这是因为list.prototype.getList()返回的是一个对象(应该是一个数组)。我也尝试过使用res.json()的方式,但也没有成功。我该怎么办? - Louis
可以了,谢谢!输出结果大概是:["AllAccounts","Cascadin...] - Louis
但我想这样做:`var tab = new Array; tab=$('#response').html(JSON.stringify(list)); alert(tab[1]); // 然后使用tab,`不幸的是它是未定义的,我该怎么做才能访问tab [1]? - Louis
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接