【问题标题】:JQuery how to do AJAX call when checkbox is clicked and send its state?单击复选框并发送其状态时,JQuery如何进行AJAX调用?
【发布时间】:2023-03-22 16:08:01
【问题描述】:

我想在用户单击复选框时进行 AJAX 调用。该调用会发送一个 id 以及复选框状态。现在,当我单击复选框时,它会创建两个 AJAX 调用,一个具有列表中的第一个 id,一个是我单击的正确的。

如何发送一个我点击的复选框的 ajax 调用?

我有数百行客户 ID 为 1000、1001、1002 等。 现在,AJAX 调用始终为 1000,并且带有我单击的客户 ID 的 ajax 调用。 假设我单击客户 ID 为 1005 的行上的复选框,那么现在的 AJAX 调用是:

testurl&cid=1000&checkbox=1
testurl&cid=1005&checkbox=1

$document.on('change', '.toggle-checkbox', function() {
  var $this = $(this);
  var customerid = $row.data('customerid');
  var checkState = '';

  if ($(this).is(':checked')) {
    checkState = 1;
  } else {
    checkState = 0;
  }
  
  $.ajax({
    url: base_url + "testurl",
    type: "GET",
    data: {
      cid: customerid,
      checkbox: checkState
    },
    success: function(result) {
      console.log('succesful change');
    },
    error: function(xhr, status, error) {
      console.log('unsuccesful change');
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<tr class="test-row" data-customerid="1000">
  <td data-content="Customer ID" class="" style="max-width:700px">1000</td>
  <td class="toggle-checkbox" data-content="">
    <div class="custom-control custom-switch no-click">
      <input type="checkbox" checked="checked" class="custom-control-input toggle-checkbox" id="">
      <label class="custom-control-label" for="">&nbsp;</label>
    </div>
  </td>
</tr>

【问题讨论】:

  • 您发布的代码有什么问题?您已经拨打了$.ajax() 电话?
  • 它触发了两次,因为您同时拥有一个 td 和一个 input,其类为 toggle-checkbox,因此单击 input bubblestd$row 变量来自哪里?此外,复选框已经具有 checked 属性,因此您可以将 checkState 简化为 this.checked + 0

标签: javascript html jquery ajax


【解决方案1】:

为什么不试试这个

  url: base_url + "testurl?cid="+ customerid+"&checkbox="+checkState,

并从 ajax 中删除“data:...”

如果还是不行的话

<input type="checkbox" id="row1000" checked="checked" class="custom-control-input toggle-checkbox" >

javascript

 var customerid = this.id.substring(3);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-18
    • 2011-03-08
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 2016-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多