Jquery:如何在ajax中添加重复数据

Jquery: How to add repeat data in ajax

本文关键字:添加 数据 ajax Jquery      更新时间:2023-09-26

我想向ajax、添加重复数据发布

但是,我不知道哪里出了问题,

请帮帮我,非常感谢~!

如果输入类使用单击,则添加活动类。

然后单击finish_sumbit获取输入employe.active.val()my console.log

但是重复就是麻烦~!

这是我的HTML

<input type="button" class="btn ahr-button_2 employ" value="bruce">
<input type="button" class="btn ahr-button_2 employ" value="peter">
<input type="button" class="btn ahr-button_2 employ" value="abcd">
<input type="button" class="btn ahr-button_2 employ" value="efgh">
<a href="#" class="finish_sumbit">完了</a>

这是我的Javascript

$('.employ').click(function(){
        $(this).toggleClass('active');
});
$(".finish_sumbit").click(function(){
 var rows = $('.employ.active');
 var employ = $('.employ.active').val();
 for(var i = 0; i < rows.length; i++)
 {
     var data = {'employ':employ[i],'test_id':'1'};
 }
 console.log(data);
$.ajax({
    type: "POST",
    url: "business_a",
    async:false,
    data: {bruce:data,_token:token},
    success: function (data) {
        alert(JSON.stringify(data));
    },
    error: function (data) {
      alert('error');
    }
});

您的代码中存在多个问题。.val()将只返回调用集中第一个元素的值,因此employ将始终是单个值。同样在循环中,您总是覆盖data 的值

由于可以有多个对象,data应该是一个数组

$('.employ').click(function() {
  $(this).toggleClass('active');
});
$(".finish_sumbit").click(function(e) {
  e.preventDefault();
  var data = $('.employ.active').map(function() {
    return {
      'employ': this.value,
      'test_id': '1'
    }
  }).get();
  console.log(data);
  $('pre').text(JSON.stringify(data, null, 2));
});
.active {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" class="btn ahr-button_2 employ" value="bruce">
<input type="button" class="btn ahr-button_2 employ" value="peter">
<input type="button" class="btn ahr-button_2 employ" value="abcd">
<input type="button" class="btn ahr-button_2 employ" value="efgh">
<a href="#" class="finish_sumbit">完了</a>
<br />
<pre></pre>

在for循环中,每个循环都初始化新的数据变量!放入var数据;在脚本开始时,in for循环将没有var

使用jQuery扩展。https://api.jquery.com/jquery.extend/