在node.js + express中实现依赖select列表

我是新来的node.js和expression。 我正在写一个node.js应用程序与快递和express-handlebars作为我的模板框架。 我想实现一个依赖的select列表,它将根据另一个select列表的select值来呈现。

到目前为止,这是我的:

这是我的家长领料单

<select id="buildingsSelect" class="building-select-add "name="residentBuildings"> {{#each buildingRows}} <option value="{{idBuildings}}" name={{Name}}>{{Name}}</option> {{/each}} </select> 

当用户select一个build筑物时,我做了一个ajax请求,

 $('.building-select-add').change(function(){ var buildingId = $('.building-select-add').val(); $.ajax({ type: 'post', url: '/resident_add/' + buildingId, success: function(data) { location.reload(); }, error: function(err) { console.log('------------ Error while updating this resident: ' + err); console.log('------------ Error while updating this resident: ' + err.message); } }); }); 

并将用于进行数据库调用的值发送到Residents数据库。

 router.post('/:buildingId', function(req, res){ var buildingId = req.params.buildingId; console.log('OOOOOO buildingId: ' + buildingId); var resList = []; connection.query('select idResidents, Name from Residents where BuildingId = ?', buildingId, function(err, rows){ if (err) { console.log('----------------------- ERROR: Error querying records - ' + err); console.log('----------------------- ERROR: ' + err.message); return err; } resList = rows; }); }); 

我想要居民在另一个select显示,但我无法填充它。

我如何渲染页面上的select? 如果我在ajax做一个location.reload()整个页面被重新加载。 有没有办法做到这一点?

通常,您要做的是创build一个返回一些JSON的Ajax请求。 然后,当浏览器的Javascript接收到JSON的时候,它会把它parsing成一个Javascript对象或数组,然后使用这些结果直接操作DOM,将它们插入到页面的列表中。

根据所需的显示,您可以将该列表插入页面上的现有元素,或者创build一个新列表并将其插入到页面中。 关键在于你正在使用Ajax调用的JSON结果,并使用客户端Javascript进行此操作。

在Ajax调用之后,你不会显示期望的HTML结果,所以我不能确切地显示如何实现这个function,而不是做一个reload() ,而只是从Ajax调用中获取JSON结果(哪个jQuery将已经被parsing成一个Javascript对象),你可以遍历它并根据需要插入到DOM中。

  $('.building-select-add').change(function(){ var buildingId = $('.building-select-add').val(); $.ajax({ type: 'post', url: '/resident_add/' + buildingId, success: function(data) { // use the data result here to insert into a picklist // in the current page }, error: function(err) { console.log('------------ Error while updating this resident: ' + err); console.log('------------ Error while updating this resident: ' + err.message); } }); }); 

我不太确定你想要从Ajax调用中返回哪些数据,但是看起来像这样:

 router.post('/:buildingId', function(req, res){ var buildingId = req.params.buildingId; console.log('OOOOOO buildingId: ' + buildingId); connection.query('select idResidents, Name from Residents where BuildingId = ?', buildingId, function(err, rows){ if (err) { console.log('----------------------- ERROR: Error querying records - ' + err); console.log('----------------------- ERROR: ' + err.message); return err; } res.json(rows); }); }); 

还有其他方法可以做到这一点。 ajax调用的结果可能是一个呈现的HTML模板,您只需将该HTML插入到页面的正确位置即可。 如果只是进入另一个下拉列表,那么这可能是没有意义的,因为只有一个下拉列表使用模板引擎没什么价值,但是如果生成的HTML有很多HTML(说明,列等等),那么你可能想使用模板引擎来创build它,而不是用Javascript手动创build它。 这一切都取决于所需的HTML结果是什么样子(你没有与我们分享)。