我想向我的Express服務器上的根目錄發出Ajax請求。AJAX發佈數據未定義?
當我剛剛使用HTML表單並提交一個藝術家的名字,我得到響應回來,可以將信息發送到客戶端就好了......
見res.send(tourDetails);
當我像這樣運行代碼時,我得到了JSON數組,並且我很好。
var express = require('express');
var app = express();
var bodyParser = require('body-parser')
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
var TourSchedule = require('./artist_profile.js');
app.use('/public', express.static(__dirname + '/public'));
app.set('view engine', 'jade');
app.set('views', __dirname + '/views');
app.get('/', function(req, res){
res.render('layout.jade');
});
app.post('/', function(req, res){
var artistName = req.body.artist_name;
var tour = new TourSchedule(artistName);
tour.on('end', function(tourDetails){
res.send(tourDetails);
});
});
app.listen(3000, function(){
console.log('Front-end server started on port 3000...');
});
但是,當我嘗試添加我的ajax post請求時遇到了麻煩。用console.log(artistName)替換res.send(tourDetails),我發現artistName是未定義的。所以當我使用HTMl表單的時候就認識到了這一點,但是當我介紹我的Ajax的時候它就會中斷。
$('#artist-form').on('submit', function(evt){
evt.preventDefault();
$.post('/', function(res){
var tourInfo = $.parseJSON(res);
var tourHTML;
$.each(tourInfo, function(ind, val){
tourHTML += '<ul class="show-details">';
tourHTML += '<li class="show-title">';
tourHTML += tourInfo[ind].title;
tourHTML += '</li>';
tourHTML += '<li class="show-date">';
tourHTML += tourInfo[ind].formatted_datetime;
tourHTML += '</li>';
tourHTML += '<li class="show-tickets">';
tourHTML += 'Tickets: ' + tourInfo[ind].ticket_status;
tourHTML += '</li>';
tourHTML += '</ul>';
});
$('.artist-tour').append(tourHTML);
}, 'json');
});
這裏的HTML ...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>snapTour</title>
</head>
<body>
<form method="post" id="artist-form">
<input type="text" id="artist-field" name="artist_name">
<button type="submit">Search</button>
</form>
<div class="artist-tour"></div>
<script src="../public/js/jquery.min.js"></script>
<script src="../public/js/jquery.js"></script>
</body>
</html>
我一直在破壞我的大腦在這幾個小時。任何意見是極大的讚賞!
看起來這樣也行不通。 奇怪的是,typeof req.body仍然說我發送一個對象,即使在序列化之後。 –
所以它不再是'未定義',而是一個對象?當你'console.log(artistName)'現在得到什麼? – adeneo
無論有無更改,console.log(req.body)都會返回空對象,並且console.log(artistName)返回undefined。我唯一能想到的是我的表單有問題,但看起來很好。 這是github,如果你覺得如此熱血沸騰。 https://github.com/danemery/snapTour –