我在Node上用服务器端运行一个简单的程序,带有cheerio。以下是代码:
服务器端:
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path')
, request = require ('request')
, cheerio = require ('cheerio')
, $;
var app = express();
//console.log($('[class = "orange"]').attr('id'));
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
request('http://localhost:3000', function (error, response, html) {
if (!error && response.statusCode == 200) {
$ = cheerio.load(html);
}
});
app.listen(3000);
var temp2=9;
app.get('/data2', function(req, res){
//var $ = cheerio.load('<body>');
//var temp = $('[class="orange"]').attr('id');
console.log(temp2);
res.send(temp2); //replace with your data here
});
app.get('/data', function(req, res){
//var $ = cheerio.load('<body>');
var temp = $('[class="orange"]').attr('id');
console.log(temp);
res.send(temp); //replace with your data here
});
&#13;
index.ejs(快速模板)
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js" type="text/javascript"></script>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1><%= title %></h1>
<input type="button" id="stopButton" value="Button1"/>
<input type="button" id="stopButton2" value="Button2"/>
<p>Welcome to <%= title %></p>
<ul id="fruits">
<li id= "1" class="apple">Apple</li>
<li id = "2" class="orange">Orange</li>
<li id = "3" class="pear">Pear</li>
</ul>
<script type="text/javascript">
$(document).ready(function () {
$('#stopButton').click(function () {
$.get('http://localhost:3000/data', {}, function (data) {
$('[id="2"]').html(data);
});
});
$('#stopButton2').click(function () {
$.get('http://localhost:3000/data2', {}, function (data2) {
console.log(data2);
$('[id="2"]').text(data2);
});
});
});
</script>
</body>
</html>
&#13;
模板会创建一个项目列表,并将其显示在 HTML 。
上HTML 上还显示 2 按钮:Button1和Button2。
当我按下Button1时,&#39; Orange&#39;更改为2。 当我按下Button2时,理想情况下Orange应该更改为9,但它不会。有什么不对吗?
两个按钮的console.log()完美地运行在控制台中显示的数字2和9。
任何帮助都将不胜感激。