简体   繁体   中英

how can i pass an array of parameters to route?

I want to delete some rows from MySQL db using checkboxes from my ejs view to routes with node.js and React app. I can delete one row, but how can i pass and array of parameters?

This is my router delete-func:

router.get("/delete/:id", function (request, res, next) {
  var id = request.params.id;
  const sql = `DELETE FROM users WHERE id = "${id}" `;

This is "delete button html code" with id for deleting one row from ejs file:

<a href="/users/delete/<%=data.id%>" class="btn btn-danger btn-sm">Delete</a>

My table

I can delete one row, but I can't delete more at once.

First of all, you should use DELETE instead of GET method to delete single row in your router.

You can use POST method to send an array of inputs to the server. So just need put a checkbox for each rows which name is "shouldDelete[]" or another name you like it.

It's important that using the brackets to send an array of inputs to the server. And then you should use a <form> to send your POST request.

Client:

<form action="/groupDelete" method="POST">
    <input type="checkbox" name="shouldDelete[]" value="ROW_ID_HERE" for="row1">
    <input type="checkbox" name="shouldDelete[]" value="ROW_ID_HERE" for="row2">
    <input type="checkbox" name="shouldDelete[]" value="ROW_ID_HERE" for="row3">
    <button type="submit">Send</button>
</form>

Server:

router.post("/groupDelete", function (request, res, next) {
  var groupIds = request.body.shouldDelete;
  const sql = `DELETE FROM users WHERE id IN ("${groupIds.join(',')}") `;

Notice: Observe safety precautions when querying the database.

      const urlencodedParser = express.urlencoded({ extended: false });   

   router.post("/groupDelete", urlencodedParser, function (request, res, next) {
      var groupIds = request.body.shouldDelete;
      const sql = `DELETE FROM users WHERE id IN (${groupIds.join(",")}) `;
      console.log(sql);
      db.query(sql, function (err, data) {
        if (err) {
          throw err;
        } else {
          res.redirect("/users/user-list");
        }
      });
    });


    <form action="/users/groupDelete" method="POST">
      <input
        type="checkbox"
        name="shouldDelete"
        id="34"
        value="34"
        for="row1"
      />
      <input
        type="checkbox"
        name="shouldDelete"
        id="36"
        value="36"
        for="row3"
      />
      <button type="submit">Send</button>
    </form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM