简体   繁体   English

我如何通过Ajax发送所选复选框的值

[英]How can i send the value of the selected checkbox through ajax

I am getting data from a backend server, and I would like to know how I can send the value of the questionid if the checkbox is clicked. 我正在从后端服务器获取data ,我想知道如果单击复选框,如何发送questionid的值。

function renderHTML(data) {
  var htmlString = "";  
  for (i = 0; i < data.length; i++) {
    htmlString += "<p><input type='checkbox' id='checks' value='" + data[i] + "'/>" +
      data[i].questionid + "." + "\n;
    htmlString += '</p>';
  }
  response.insertAdjacentHTML('beforeend', htmlString);
  document.getElementById('checks').onclick = function() {
    if (this.checked) {
      var xhr = new XMLHttpRequest();
      xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
          var Data = xhr.responseText;
          var parseData = JSON.parse(Data);
          console.log(parseData);
        }
      };
      xhr.open("POST", "URL", true);
      xhr.send(JSON.stringify(data));
    }
  };
}

I suggest you use name instead id 我建议您使用名称代替id

id='checks' => name='checks' And define fuction like this link id ='checks'=> name ='checks'并定义此链接的功能

The basic idea of what you're asking is doable, see the code snippet below. 您所要求的基本概念是可行的,请参见下面的代码段。 Instead of logging the result, you can replace that with whatever AJAX call you need to do. 除了记录结果,您还可以将其替换为所需的任何AJAX调用。

Note: One of the big issues in your code (aside from the quotation-related syntax error), is that you're trying to assign id="checks" to multiple HTML elements, which you can't do. 注意:您代码中的主要问题之一(除了与报价相关的语法错误外)是,您试图将id="checks"分配给多个HTML元素,而您不能这样做。 When you do this, generally your onclick event will work for the first element, but not the rest. 执行此操作时,通常, onclick事件将对第一个元素起作用,而对其余元素不起作用。 Instead, use classes , or, use the querySelector like I have below. 而是使用classes ,或者像下面一样使用querySelector

 var checkboxes = document.querySelectorAll('input[type="checkbox"]'); for (var i=0; i < checkboxes.length; i++) { checkboxes[i].onclick = function() { if (this.checked) { console.log(this.value + ' is checked!'); } } } 
 <input type="checkbox" value="checkbox 1" /> <input type="checkbox" value="checkbox 2" /> <input type="checkbox" value="checkbox 3" /> 

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

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