如何将具有动态生成的ID的字符串值添加到Ajax发布数据中

问题描述 投票:0回答:1

我通过单击“ +”按钮从我的html中动态生成了具有唯一ID(item1,item2,item3等)的文本类型输入。我试图通过使用动态生成的ID发布所有值$ .ajax({方法:“ POST”,网址:“ / addItems”,输入:“ POST”,数据:{项目:$('#item'+ count).val()}但是,没有任何数据传递给我的数据数组。我尝试使用“ item1”而不是“ item” + count,它可以工作,但它只是我的html中已经存在的一个值。我也尝试使用dataForm或for循环,但是没有用。有谁知道如何将所有值传递到我的javascript文件中称为“ items”的数组?有关更多详细信息,下面是我的代码段(忽略css文件。它是要运行的代码段):

const express = require("express");
const app = express();
    app.use(express.urlencoded({extended: true}));
    app.use(express.static("public"));
    app.set("view engine", "ejs");
    app.use(express.json());
    var items = [{item: 'study Node.js'}, {item: 'play Overwatch'}];
    
    app.get('/myForm', (req, res) => res.render("pages/myForm"));
    app.get('/result', (req, res) => res.render("pages/result", {
    items:items}));

    app.post('/addItems', (req, res) => {
        console.log(req.body);
        items.push(req.body);
        res.json({success: 'true'});
        

    });
    app.listen(3000);
h1 {
    grid-area: itemNumber;
    color: white;
    font-family: monospace;
    margin-left: 10px;
    display: inline;
}

input {
    background-color: #DEFDE0; 
    border-radius: 5px; 
    border: 1px solid; 
    outline: none; 
    overflow: auto;
    grid-area: textarea;
    margin-top: 20px;
    width: 150px;
    margin-left: 5px;
}

button {
    grid-area: plus;
    padding: 7px;
    width: 35px;
    border: 1px solid;
    outline: none;
    border-radius: 5px;
    margin-top: 22px;
    margin-left: 5px;
}

#submit {
    background-color: #F0DEFD; 
    border-radius: 5px; 
    border: 1px solid; 
    position: static;
    grid-area: send;
    padding: 7px;
    width: 60px;
}

body {
    background-color: black;

}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.0.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <link rel="stylesheet" type="text/css" href="myFormStyle.css">
    <title>My Form</title>
</head>
<body>
<!-- Create your form here -->
<div class="container">
    <br/>
    <br/>
    <div class="form-group">
        <form name="add_name" id="add_name" method="post">
            <div class="table table-bordered" id="item_field">
                    <h1>Todo Item 1</h1>
                    <input type="text" name="name[0]" id="item1" class="task" cols="22" rows="2">
                    <button type="button" name="add" id="add" class="addButton">+</button></td>
            </div>
            <input type="button" name="submit" id="submit" value="Submit"/>
        </form>
    </div>
</div>
</body>
</html>
<script>
    $(document).ready(function() {
        var count = 1;
        var $itemIds = Array.from($('h1 + .task'))
        var ids = $itemIds.map(task => $(task).attr('id'))
        $('#add').on('click', function() {
            count++;
            $('#item_field').append('</br><h1>Todo Item ' + count +'</h1><input type="text" name="name['+ (count - 1) +']" id="item'+ count +'" class="task" cols="22" rows="2">');
            $('#add').insertAfter('#item' + count);
        }); 
        $('#submit').on('click', function() {
        $.ajax({
            method: 'POST',
            url:'/addItems',
            type: 'POST',
            data: {
                item: $('#item' + count).val()
            }
        }).
        done(function(data) {
        console.log(data);
        console.log(ids);
        alert(data.success);
        }).
        fail(function(error) {
        console.log(error);
        })
    })       
    });



</script>
javascript jquery node.js ajax ejs
1个回答
0
投票

您需要遍历所有元素来为数据构建items数组,如下所示:

h1 {
  grid-area: itemNumber;
  color: white;
  font-family: monospace;
  margin-left: 10px;
  display: inline;
}

input {
  background-color: #DEFDE0;
  border-radius: 5px;
  border: 1px solid;
  outline: none;
  overflow: auto;
  grid-area: textarea;
  margin-top: 20px;
  width: 150px;
  margin-left: 5px;
}

button {
  grid-area: plus;
  padding: 7px;
  width: 35px;
  border: 1px solid;
  outline: none;
  border-radius: 5px;
  margin-top: 22px;
  margin-left: 5px;
}

#submit {
  background-color: #F0DEFD;
  border-radius: 5px;
  border: 1px solid;
  position: static;
  grid-area: send;
  padding: 7px;
  width: 60px;
}

body {
  background-color: black;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.0.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
  <link rel="stylesheet" type="text/css" href="myFormStyle.css">
  <title>My Form</title>
</head>

<body>
  <!-- Create your form here -->
  <div class="container">
    <br/>
    <br/>
    <div class="form-group">
      <form name="add_name" id="add_name" method="post">
        <div class="table table-bordered" id="item_field">
          <h1>Todo Item 1</h1>
          <input type="text" name="name[0]" id="item1" class="task" cols="22" rows="2" />
          <button type="button" name="add" id="add" class="addButton">+</button>
        </div>
        <input type="button" name="submit" id="submit" value="Submit" />
      </form>
    </div>
  </div>
  <script>
    $(document).ready(function() {
      var count = 1;
      var $itemIds = Array.from($('h1 + .task'))
      var ids = $itemIds.map(task => $(task).attr('id'))
      $('#add').on('click', function() {
        count++;
        $('#item_field').append('<br><h1>Todo Item ' + count + '</h1><input type="text" name="name[' + (count - 1) + ']" id="item' + count + '" class="task" cols="22" rows="2">');
        $('#add').insertAfter('#item' + count);
      });
      $('#submit').on('click', function() {
        var items = [];
        for (let i = 1; i <= count; i++) { // iterate through all of the items
          items.push($('#item' + i).val());
        }
        console.log(items);
        $.ajax({
          method: 'POST',
          url: '/addItems',
          type: 'POST',
          data: {
            item: items
          }
        }).done(function(data) {
          console.log(data);
          console.log(ids);
          alert(data.success);
        }).fail(function(error) {
          console.log(error);
        });
      });
    });
  </script>
</body>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.