weixin_33743248
weixin_33743248
2019-08-03 11:30
采纳率: 0%
浏览 184

重定向后获取数据

I've a page '/order/new' that include 2 dropdown menues for customer & its address & a button that redirect to choose product to add to the order and I get the products in an array and pass the array to the '/order/new'..but when i redirect I don't get the selected customer & its address..I save the products which will be added in order in global array called hh which its get the data from ajax

I want to get the customer & its address after adding the product array


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);

my ajax code:

////////////////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);
                }
              })
               })

My ejs for'/new/order':

<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>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • weixin_33716557
    weixin_33716557 2019-08-03 11:50

    in these lines,

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

    are you successfully getting all products from your DB back?

    because in your AJAX call,

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

    you're sending data, but not using it in your 'query1' here,

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

    I'm trying to get the flow of your program.

    So the user goes to your webpage, they select a product, your webpage pings your REST server with the product information, your REST server pings your database looking for that product, then that data is rendered to this template here?

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

    EDIT: You have to handle the user interaction with event listeners and the user input with some storage method.

    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);
    

    I recommend the cookie method. You set the cookie once, use it when you need it, then delete it when you're done.

    With the first method, you have to send the data in your fetch (which doesn't need that data to get the products), then you have to manage that user_data throughout your back-end making sure it doesn't get lost. It's too much work. Use the cookie method instead.

    点赞 评论

相关推荐