简体   繁体   English

如何使用 for 循环将 Json object 推送到 Json 数组?

[英]How to push Json object to Json array using for loop?

I have a html table where onclick dynamically rows added.我有一个 html 表,其中 onclick 动态添加了行。 I need to convert that row textbox values into JSON array.我需要将该行文本框值转换为 JSON 数组。

Note: Ajax must be used because I need to save data to sql server .注意:必须使用Ajax因为我需要将数据保存到sql server

Here is my attempt.这是我的尝试。

$(function() {
  $("[id*=btnSave]").click(function() {
    $("[id*=data_table] tbody").each(function() {
      var arr = [];
      var user = {};
      for (i = 0; i <= 1; i++) {
        user.DueDate = $(this).find('tr:eq(' + i + ') td:eq(0) input').val();
        user.DueAmount = $(this).find('tr:eq(' + i + ') td:eq(1) input').val();
        arr.push(user); // Json array has every json object value
        $.ajax({
          async: true,
          cache: false,
          type: "POST",
          url: "Default.aspx/Save",
          data: JSON.stringify(user),
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          success: function(response) {
            alert("Data added successfully.");
            alert(JSON.stringify(user)); //Json object value //Alert 2
            alert(JSON.stringify(arr)); //Json array value  //Alert 3
          }
        }); //End of ajax
        return false;
      } //End of for loop
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table cellspacing="3" cellpadding="3" id="data_table" width="50%">
  <thead>
    <tr>
      <th width="30%">Due date</th>
      <th width="26%">Amount Due</th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td width="30%">
        <input type="text" id="Text1" autocomplete="off" placeholder="Due Date" runat="server" />
      </td>
      <td width="25%">
        <input type="text" runat="server" id="new_Amount_1" placeholder="0.00" autocomplete="off" />
      </td>
      <td>
        <input type="button" value="Delete" />
      </td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>
        <input type="button" value="Add row" id="btnAddRow" />
        <input type="button" value="Save" id="btnSave" />
      </td>
    </tr>
  </tfoot>
</table>

I used for loop to get every dynamically added row values.我使用for loop来获取每个动态添加的行值。 My output should be like this.我的output应该是这样的。 Alert2 Json object format Alert2 Json object 格式

{"DueDate":"17/09/2019","DueAmount":"100"}

Alert3 Json array format Alert3 Json 数组格式

[{"DueDate":"17/09/2019","AmountDue":"100"},{"DueDate":"18/09/2019","AmountDue":"200"},{"DueDate":"19/09/2019","AmountDue":"300"}]

But in My output Alert3 I am getting first object only但是在我的 output Alert3中,我只得到第一个 object

[{"DueDate":"17/09/2019","DueAmount":"100"}]

What I have done wrong?我做错了什么? I think for loop is not correct.我认为 for 循环是不正确的。 Please help me with that.请帮帮我。

Instead of looping this, you can directly use the serializeArray or serialize if you need a custom format如果需要自定义格式,您可以直接使用serializeArray序列化,而不是循环这个

 $("form").on("submit", function(event) { event.preventDefault(); console.log($(this).serializeArray()); $.ajax({ async: true, cache: false, type: "POST", url: "Default.aspx/Save", data: JSON.stringify($(this).serializeArray()), contentType: "application/json; charset=utf-8", dataType: "json", success: function(response) { console.log("Data added successfully."); } }); //End of ajax });
 <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script> <form> <table cellspacing="3" cellpadding="3" id="data_table" width="50%"> <thead> <tr> <th width="30%">Due date</th> <th width="26%">Amount Due</th> <th></th> </tr> </thead> <tbody> <tr> <td width="30%"> <input type="text" name="Text1" autocomplete="off" placeholder="Due Date" runat="server" /> </td> <td width="25%"> <input type="text" runat="server" name="new_Amount_1" placeholder="0.00" autocomplete="off" /> </td> <td> <input type="button" value="Delete" /> </td> </tr> </tbody> <tfoot> <tr> <td> <input type="button" value="Add row" id="btnAddRow" /> <input type="submit" value="Save" id="btnSave" /> </td> </tr> </tfoot> </table> </form>

Yes, you can use.serialize() or.serializeArray() and these two functions only runs on a form tag.是的,您可以使用 .serialize() 或 .serializeArray() ,这两个函数仅在表单标签上运行。

In your code if you are adding tr tag each time that you press btnAddRow, your for loop is wrong:在您的代码中,如果您每次按 btnAddRow 时都添加 tr 标签,则您的 for 循环是错误的:

for (i = 0; i <= 1; i++) 

Replace with:用。。。来代替:

for (i = 0; i <= $(this).find('tr').length; i++) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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