我有一个页面“ / order / new”,其中包括两个用于客户及其地址的下拉菜单,以及一个用于重定向以选择要添加到订单中的产品的按钮,然后将产品放入数组并将数组传递到“ / order / new'..但是当我重定向时,我没有得到选定的客户及其地址..我将要按顺序添加的产品保存在名为hh的全局数组中,该数组从ajax获取数据

添加产品阵列后,我想获得客户及其地址


global.hh = new Array();

module.exports = {

getProduct: (req , res ) => {
  var products = req.query.selectedProduct;
  var total = req.query.sumTotal;
 var btekh = hh.push(products)
}
getOrderProduct: (req , res) => {
  let query1 = "SELECT * FROM `product`";
  getConnection().query(query1 ,(err , result) => {
    if(err) {
     return res.status(500).send(err);
    }
    res.render('productOrder.ejs' , {
      products: result
    });
  });
},
addOrderProduct: (req, res) => {
  res.redirect('/order/new')
}


postOrder: (req ,res) => {
  var products = req.session.products;
    getConnection().query('INSERT INTO `order` ( clientId , addressId,orderStatusId) VALUES (?,?,?)', [req.body.selectUser, req.body.selectAddress,req.body.selectedStatus], (err,result) => {
    if (err) {
      console.log(err);
    }
  hh.slice(-1)[0].forEach(function (item) {
    let insertedOrder = result.insertId;
    let query = "INSERT INTO `orderProduct`( `orderIdProduct`, `productId`, `orderProductName`,`orderProductPrice`, `orderProductQuantity`, `orderProductTotal`) VALUES (?,?,?,?,?,?)";
    getConnection().query( query , [insertedOrder,item.check,item.name,item.p,item.q,item.total] , (err , result)=>{
      if (err) {
        console.log(err);
      }
      res.end();
  })
})
})
}
  res.redirect('/')
}
app.get('/order/new' , addOrderPage)
app.use('/postOrder' , postOrder);
app.use('/order/product' , getProduct);



我的ajax代码:

////////////////add users's address///////////////////////////
 $('#user').change(function(){

    var item = $('#user').val();
    $.ajax({
        type:'GET',
        data: { selectedId: item },
        url:'/users/address',
        success: function(data){
             $('#address').empty();
         $('address').append("<option disabled selected> Select Address..</option>");
         $.each(data, function (index, addressObj) {
                $('#address').append("<option value = '" + addressObj.addressId + "' > " + addressObj.addressName + " </option > ");
            });
        }
    });
   })

;
//////////////get the product to order/////////////
     $('#save').click(function () {
        var orderProduct = new Array();
        $("#table input[type=checkbox]:checked").each(function () {
                      var row = $(this).closest("tr");
                      var message0 = row.find('#check').val();
                      var message1 = row.find('.name').text().trim();
                      var message3 =  row.find('.currency').text().trim();
                      var message4 =  row.find(".foo").val();
                      const result =  {check: message0,name: message1,p: message3,q:  message4 ,total: message3 * message4}
                      var hh = orderProduct.push(result);
                });
                console.log(orderProduct);
                var totalPrice = 0;
             orderProduct.forEach(function (item , index) {
                totalPrice = totalPrice + item.total
              })
              $.ajax({
                type: 'GET',
                data: {selectedProduct: orderProduct , sumTotal: totalPrice},
                url: '/order/product',
                success: function (data) {
                  console.log(data);
                }
              })
               })


我的'/ new / order'的ejs:

<header>
        <h2>New Order : </h2>
      </header>
      <form action="/postOrder" method="post" id="newForm" >
        <label> User Name:</label>
        <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>
        <br>
        <label>Product</label>
      <a href="/orderProduct" id="addProduct"> add product</a>
        <br>
        <label>Status</label>
        <select name="selectedStatus">
        <% status.forEach((status) => { %>
            <option value="<%= status.statusId %>"> <%= status.statusText %></option>
        <%  })  %>
      </select>
      <br>
        <input type="submit" value="Save">
      </form>

最佳答案

在这些方面,

res.render('productOrder.ejs' , {
      products: result
    });


您是否成功从数据库中获取了所有产品?

因为在您的AJAX通话中,

$.ajax({
            type: 'GET',
            data: {selectedProduct: orderProduct , sumTotal: totalPrice},
            url: '/order/product',
            success: function (data) {
              console.log(data);
            }
          })


您正在发送数据,但未在此处的“ query1”中使用它,

let query1 = "SELECT * FROM `product`";


我正在尝试获取您的程序的流程。

因此,用户转到您的网页,他们选择一种产品,您的网页用产品信息ping您的REST服务器,您的REST服务器ping您的数据库以查找该产品,然后将数据呈现到此处的模板中?

res.render('productOrder.ejs' , {
      products: result
    });


编辑:您必须处理与事件侦听器的用户交互以及使用某种存储方法的用户输入。

Your_client-side_JS_script.js

function handle_submit(e) {
  e.preventDefault();
  if (e.target.id === 'addProduct') {
    // When they click add product, you need to either pass their user details to the route and send them with the $.ajax GET request
    //... and keep track of the data like that
    // OR
    // track that data in a cookie,
    read up on cookies https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie
  } else if (e.target.id === 'newForm') {
    console.log("Submit Form");
  }
};
$('#addProduct').on('click', handle_submit);
$('#newForm').on('submit', handle_submit);


我建议使用cookie方法。设置一次cookie,在需要时使用它,完成后将其删除。

使用第一种方法,您必须在获取中发送数据(不需要该数据即可获得产品),然后必须在整个后端管理该user_data,以确保不会丢失它。辛苦了改用cookie方法。

关于mysql - 重定向后获取数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57337905/

10-11 10:26
查看更多