jQuery-通过ID将数据从PHP传输到JavaScript+jQuery


jQuery - Transfer Data by ID from PHP to JavaScript + jQuery

我有一个列表,其中有很多由(MongoDB-)ID标识的条目(100+)。每个条目都在一个html表中,并有一个复选框。当用户现在选择一个组时,我需要查询服务器是否每个条目都在特定的组中。获取会员资格的查询不太重,但我不能执行100多次,这太重了。

目前,我有用于获取组成员资格的php代码(太长了,无法发布)和以下javascript代码,每当更改选择时都会执行:

$('checkbox[data-type="group"]').each(function(idx, val) {
  // get the ID and set it checked/unchecked
});

我的问题是:如果条目在所选组中,我如何能高效地查询服务器一次,然后检查每个ID?

您的问题有点难以理解,但我认为您应该发布一个JSON列表并将其发布在一个查询中,并在服务器端处理迭代,如下所示:

id_list = {};
$('checkbox[data-type="group"]').each(function(idx, val) {
  the_id = //get the id into a variable somehow;
  id_list[the_id] = val;
});
$.ajax({
  url: "some url",
  dataType: "json",
  type: "post",
  data:id_list
}).done(function(data) {
 //using returned data, set each to check/unchecked
 //assuming that the returned data had format of id:boolean, and the boolean defines whether it should be checked (e.g. {1: true, 2: false, 3: false}   )
 $.each(data, function(index,value) {
  if (value == true) {
    $('checkbox#'+index).attr('checked',true);
  } else {
    $('checkbox#'+index).attr('checked',false);
  }
});

如果这不能回答你的问题,那么请更详细地重新表述你的问题。