从HTML页面执行Nodejs脚本?

我目前正在使用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);

索引咖啡

doctype 5

html ->

head ->

body

p->“嘿”

回答:

我使用普通的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

以上是 从HTML页面执行Nodejs脚本? 的全部内容, 来源链接: utcz.com/qa/436214.html

回到顶部