1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > node.js require 自动执行脚本 并生成html 从HTML页面执行Nodejs脚本?

node.js require 自动执行脚本 并生成html 从HTML页面执行Nodejs脚本?

时间:2018-08-18 16:39:49

相关推荐

node.js require 自动执行脚本 并生成html 从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 /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)。:

Get this List

$(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('/request', function(list) {

$('#response').html(list); // show the list

});

});

});

如果将 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在您的服务器上运行。然后前往/index.html

-07-07

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。