从html页面执行Nodejs脚本? [英] execute a Nodejs script from an html page?

查看:329
本文介绍了从html页面执行Nodejs脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  console.log(list); 



从控制台运行脚本时没有问题:节点请求。 js



我的问题是:如何使我的页面上的获取此列表按钮通过显示列表(即在服务器上执行 request.js 并显示结果)?



.js

  / ** 
*模块依赖项。
* /

var express = require('express')
,routes = require('./ routes');

var app = module.exports = express.createServer();

//配置

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 - >hey

server.js ):

  var express = require('express'),
list = require('./ request.js ')。请求; // see template

var app = express.createServer();

app.use(express.static(__ dirname +'/ public')); //暴露index.html,如下

app.get('/ request',function(req,res){
//运行你的request.js脚本
/ /当index.html将ajax调用到www.yoursite.com/request时,这将运行
//您还可以将您的request.js作为一个模块(上面)并调用:
res .send(list.getList()); // try res.json()如果getList()返回一个对象或数组
});

app.listen(80);

写入 index.html 将其保存到您的节点应用程序目录(其上面,通过 express.static )的 / public 子文件夹中。 :

 < html> 
< body>
< div id =button>获取此列表< / 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(){
//运行一个AJAX get请求...
//使用相同的域
尊重跨域策略//用于访问您的index.html文件!
$ .get('http:// www .yoursite.com / request',function(list){
$('#response')。html(list); //显示列表
});
});
});
< / script>
< / body
< / html>

如果您将 request.js 可以如下:

  var RequestClass = function(){
//运行代码
};

// ...添加一个方法,我们在这个例子中做:
RequestClass.prototype.getList = function(){
returnMy List;
};

//现在使用module.exports公开:
exports.Request = RequestClass;

在您的服务器上运行节点server.js 。然后前往 www.yoursite.com/index.html


I am currently using Express.js to create my website. My main server script is called index.coffee. I also created a script called request.js that makes a GET request and displays the response with

  console.log(list);

I have no problems when running the script from the console: node request.js

My question is: How do I make the "Get this list" button on my the page respond to a click by displaying the list on the same page (that is, executing request.js on the server and showing the result)?

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

解决方案

I use plain JS and not coffee script, so here's an example per Fosco's comment (call it 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);

Write your index.html file, and save it in the /public subfolder of your node app directory (which is exposed above, via 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>

If you're including your request.js as a module, it could be as follows:

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;

Run node server.js on your server. Then head over to www.yoursite.com/index.html

这篇关于从html页面执行Nodejs脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆