【问题标题】:execute a Nodejs script from an html page?从 html 页面执行 Nodejs 脚本?
【发布时间】:2012-03-29 00:55:40
【问题描述】:

我目前正在使用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 -> “嘿”

【问题讨论】:

  • 您应该创建一个请求处理程序(就像您对索引页面所做的那样),它执行 request.js 中的代码...您可以使用 Ajax 调用来拉回这些数据并将其加载到页面。
  • 好的,你有任何关于请求处理程序的教程和一个能够把这些数据拉回来的 ajax 方法吗?^^?我对节点和 Ajax 真的很陌生。并感谢您的回答!
  • 您应该照原样发布您的代码。我不使用咖啡脚本,所以我无法提供完整的解决方案,但肯定会有其他人能够提供帮助(如果代码在这里。)
  • 我会这样做然后谢谢:)(html中的解决方案对我来说也很好^^)

标签: javascript node.js coffeescript express


【解决方案1】:

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

【讨论】:

  • 好吧,我试过了(顺便说一句,我用 &lt;button id="button"&gt;.. 替换了 &lt;div id="button"&gt;,(它只工作了 1 次,但是 nvm)我对这条线感兴趣:// you can also require your request.js as a module, and export a function from it ,我该怎么做这很有趣,因为当我执行 var list = require('request.js'); 时,它说它没有 POST 方法。我怎样才能避免这个错误?
  • 当您单击按钮时,它将完全替换 div#response 的内容,如果内容相同,这可能看起来只工作 1 次。否则,您可能必须重新绑定附加到 #button 的点击事件。
  • 我将更新我的答案以包括如何将 request.js 用作模块。我不确定为什么它会说你没有 POST 方法。我的猜测是您在 list 上调用了一个未公开或未定义的方法。
  • 嘿,除此之外一切正常:当我尝试res.send("sent"); 时,它可以工作,但res.send(list.prototype.getList();) 不能工作,我认为因为list.prototype.getList() 返回一个对象(应该是一个数组)(我也试过res.json() 方式,也不行。我该怎么办?
  • res.json() 似乎工作,确实当我点击get this list 如果在response div 中有一个文本(任何东西),这个文本消失了,但是对象没有显示,我不明白为什么。再次感谢
猜你喜欢
  • 2011-10-12
  • 2021-12-06
  • 1970-01-01
  • 2018-10-04
  • 1970-01-01
  • 2014-03-21
  • 1970-01-01
  • 1970-01-01
  • 2021-04-11
相关资源
最近更新 更多