我是Node的新手。我需要制作一个从属下拉菜单,该菜单从同一页面中的另一个下拉菜单中获取选定用户的地址数据。问题是不仅更新了第二个下拉菜单,还更新了孔页面。我认为这是相同的问题就像dynamically dropdown in nodejs mysql一样,但这并没有太大帮助。
<select name="selectUser" id="user" >
<option disabled selected> Select User..</option>
<% users.forEach((users) => { %>
<option value="<%= users.id %>" > <%=users.name %> </option>
<% }) %>
</select>
<br>
<label>Address :</label>
<select name="selectAddress" id="address">
<option disabled selected> Select Address..</option>
<% address.forEach((address) => { %>
<option value="<%= address.addressId %>" > <%=address.addressName %> </option>
</select>
<% }) %>
我的ajax请求:
$(document).ready(function(){
$('#user').change(function(){
var item = $('#user').val();
var add = $('#address').val();
$.ajax({
type:'GET',
data: {selectedId : item },
url:'/order/new',
success: function(result1){
$('#body').html(result1);
}
});
});
});
order.js
module.exports = {
addOrderPage: (req, res) => {
let query1 = "SELECT * FROM users";
getConnection().query(query1, (err, result1) => {
let query2 = "SELECT * FROM address WHERE userId = '" +req.query.selectedId + "'";
getConnection().query(query2, (err, rows, fields) => {
if (err) {
return res.status(500).send(err);
}
console,log(rows)
res.render('newOrder.ejs', {
address : rows,
users: result1
});
});
});
}
}
app.js
app.get('/order/new', addOrderPage)
答案 0 :(得分:0)
您的成功功能缺少从请求返回的数据更新您的成功功能
$(document).ready(function(){
$('#user').change(function(){
var item = $('#user').val();
$.ajax({
type:'GET',
data: { selectedId: item },
url:'/users/address',
success: function(data){
console.log(data);
$('#address').empty();
$('address').append("<option disabled selected> Select Address..</option>");
$.each(data, function (index, addressObj) {
$('#address').append("<option value = '" + addressObj.id + "' > " + addressObj.first_name + ". </option > ");
});
}
});
});
在您的order.js中,您需要为用户创建一个呼叫,为用户创建一个呼叫地址数据
module.exports = {
addOrderPage: (req, res) => {
var selecteduser = req.query.selectedId;
let query1 = "SELECT * FROM users";
db.query(query1, (err, result1) => {
if (err) {
return res.status(500).send(err);
}
res.render('newOrder.ejs', {
players: result1,
});
});
},
getUserAddress: (req, res) => {
var selecteduser = req.query.selectedId;
let query1 = "SELECT * FROM address WHERE userId = '" + selectedId + "'";
db.query(query1, (err, result1) => {
if (err) {
return res.status(500).send(err);
}
res.send(result1);
});
}
}
neworder.js
<select name="selectUser" id="user" >
<option disabled selected> Select User..</option>
<% users.forEach((users) => { %>
<option value="<%= users.id %>" > <%=users.name %> </option>
<% }) %>
</select>
<br>
<label>Address :</label>
<select name="selectAddress" id="address">
<option disabled selected> Select Address..</option>
</select>
在您的app.js或index.js中,您需要添加其路由
app.use("/users/address", order.getUserAddress);