从HTML页面执行Nodejs脚本?

从HTML页面执行Nodejs脚本?,第1张

从HTML页面执行Nodejs脚本

我使用普通的JS而非咖啡脚本,因此这是每个Fosco注释(称为

server.js
)的示例:

var express = require('express'),    list = require('./request.js').Request; // see  templatevar app = express.createServer();app.use(express.static(__dirname + '/public')); // exposes index.html, per belowapp.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 pre 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



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5427997.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存