Tôi đã cố gắng thực hiện yêu cầu gửi AJAX với JQuery đến máy chủ Node.JS của tôi trong Node.JS và Express, nhưng nó không hoạt động!Yêu cầu gửi JQuery Ajax với node.js và thể hiện
var express = require('express')
var app = express();
app.listen(8888);
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', express.bodyParser(), function (req, res){
console.log(req);
console.log('req received');
res.redirect('/');
});
Và đây là ajax.ejs
:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
$('#enter').click(function(){
$.ajax({
url: '/ajax',
type: 'POST',
cache: false,
data: { field1: 1, field2: 2 },
success: function(data){
alert('Success!')
}
, error: function(jqXHR, textStatus, err){
alert('text status '+textStatus+', err '+err)
}
})
});
</script>
</head>
<body>
<form>
<input type="button" id="enter" value="Enter">
</form>
</body>
</html>
Khi ajax.ejs
được nạp, không có bất kỳ đầu ra trong giao diện điều khiển, vì vậy, yêu cầu bài đã không làm việc. Tôi có thể làm gì?
Xin cảm ơn!
di chuyển express.bodyParser() để các app.use() phần: app.use (express.bodyParser ()); Nội dung của bài đăng bạn có thể truy xuất qua req.body. – asgoth
Xong! Vì vậy, tôi thay đổi 'console.log (req);' thành 'console.log (req.body);'. Nhưng yêu cầu bài viết vẫn không hoạt động, tôi không có bất kỳ đầu ra nào trong bảng điều khiển. – MrMangado