【发布时间】:2017-03-31 23:38:05
【问题描述】:
我的问题是,我无法在我的 NodeJS 和 MongoDB 上使用 AJAX(发布)检索数据。我正在使用正文解析器。我使用发布请求,因为数据将取决于我的第一个下拉列表的值。
这是我的代码
NodeJS
app.get('/test', function(req, res){
City.findOne({'thecity': 'Auckland'}).populate('coolplaces').exec(function(err, thecoolplace){
if(err){
console.log(err);
} else {
res.send(thecoolplace);
}
});
});
app.post('/testpost', function(req, res){
City.findOne({'thecity': req.body.thecityname}).populate('coolplaces').exec(function(err, thecoolplace){
if(err){
console.log(err);
} else {
res.send(thecoolplace);
}
});
});
EJS
<select id="cities" name="thecityname">
<% City.forEach(function(city){ %>
<option val="<%= city.thecity %>"><%= city.thecity %></option>
<% }); %>
</select>
<select id="coolplace" name="thecities">
</select>
所以基本上,我有 2 个下拉列表,我的目标是,在我的第一个下拉列表中,它包含城市名称,然后当我在上面选择一个城市名称时,它应该用基于该城市的地方填充第二个下拉列表(我已经处理了数据库中的数据)。
正如您在我的 NodeJS 代码中看到的那样,起初,我尝试使用 GET 请求,然后根据其名称查询数据库,并使用硬编码的“Auckland”,找到了 ajax 调用,它填满了第二个奥克兰地区的下拉菜单。
现在,由于我的目标是根据第一个下拉列表中的选定值填充第二个表单,因此我创建了一个发布请求,代码相同,但查询值将取决于“req.body.thecityname”,即“我的标签的名称。
现在这是我的 Ajax 代码
$('#cities').change(function(){
theAjax();
});
function theAjax(){
console.log($('#cities').val())
$.ajax({
type: 'POST',
url: '/testpost',
data: $('#cities').val(),
success: function(data){
console.log(data);
},
error: function(){
alert('No data');
}
});
}
function fillupPlaces(){
var $coolplaces = $('#coolplace');
$.ajax({
url: '/test',
type: 'GET',
dataType: 'json',
success: function(data){
data.coolplaces.forEach(function(thecoolplaces){
$coolplaces.append('<option>' + thecoolplaces.theplacename + '</option>');
});
}
});
}
每当第一个下拉列表中的值发生变化时,Ajax 将触发,在第一行,我 console.log 它的值并返回我选择的数据的值,但是在 Ajax 成功时,控制台.log(data) 什么也不返回。
第二个功能有效,但我想要的是,用基于城市的地点填充第二个下拉列表
这是截图
我做错了什么?谢谢你们!
【问题讨论】: