我是 node.js 开发的新手,我有一个特殊的问题。我想使用 node.js 创建一个单页 Web 应用程序,用户将提交请求数据,然后从 imdb api 获取数据并将它们显示在同一页面上。我的代码如下
服务器.js
#!/usr/bin/env node
var express = require('express');
var app = express();
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
var fs = require('fs');
var inputFile = fs.readFileSync('index.html').toString();
console.log(inputFile);
app.get('/', function(request, response) {
response.send(inputFile);
});
var port = process.env.PORT || 8080;
app.listen(port, function() {
console.log("Listening on " + port);
})
app.post('/', function(req, res){
if (req.body.mysearch == ""){
var search = "heroes";
}else{
var search = req.body.mysearch;
}
console.log(search);
var http = require('http');
http.get("http://www.imdbapi.com/?t=" + search, function(res) {
console.log("Got response: " + res.statusCode);
var data = '';
res.on('data', function (chunk){
data += chunk;
})
res.on('end',function(){
// the whole of webpage data has been collected. parsing time!
var obj = JSON.parse(data);
console.log( obj.Title );
})
}).on('error', function(e) {
console.log("Got error: " + e.message);
})
});
索引.html
<html>
<head>
<meta charset="utf-8">
<title>Title of the document</title>
</head>
<body>
<form id="myform" method="post" action="/"enctype="application/x-www-form-urlencoded">
<input type="text" id="search" name="mysearch">
<input type="submit" id="mysubmit" value="Search IMDB">
</form>
<div id="myTitle">
</div>
</body>
</html>
到目前为止,代码已成功解析来自 imdb 的数据并在控制台上显示它们。问题是我将如何在网页上打印它们(例如在 div 标签上)而不重新加载页面(ajax)