这是express.js服务器代码:
var express = require('express')
var app = express();
app.listen(8001);
app.configure(function(){
app.use(express.bodyParser());
app.set('views',__dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
app.use(express.cookieParser());
app.use(app.router);
});
app.get('/', function (req, res){
res.render('ajax.ejs');
});
app.post('/ajax', function (req, res){
console.log(req.body);
res.contentType('json');
console.log(JSON.stringify({response:'json'}));
res.write(JSON.stringify({response:'json'}));
res.end();
});
这是来自ajax.ejs
的代码:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
</head>
<body>
<form>
<input type="button" id="enter" value="Enter">
</form>
<script type="text/javascript">
$('#enter').click(function(){
$.ajax({
url: '/ajax'
, type: 'POST'
, cache: false
, data: { field1: 1, field2: 2 }
, complete: function() {
//called when complete
console.log('process complete');
},
success: function(data) {
alert(data);
console.log('process sucess');
},
error: function() {
console.log('process error');
},
});
});
</script>
</body>
</html>
我正在尝试响应AJAX post req,但当ajax.ejs
向我显示服务器发送的警报中的数据时,结果为[object Object]
。这里的问题在哪里?
谢谢你!