在Ajax中发送Checkbox True或False

时间:2018-03-28 19:54:29

标签: javascript jquery html ajax

我想将bool发送到我的Node.js服务器。目前,我发送了string。我希望bool作为bool发送,而不是字符串。对我来说似乎应该是;但是,在我的mongodb数据库中,它存储为字符串。提前谢谢!

$.ajax({
  type: "POST",
  url: "url",
  timeout: 2000,
  data: {
    'bool': $('input[name=bool]').is(':checked')
  },
  success: function(data) {
    $('#Error').css('display', 'none')
    $('#Error').html('')
    $('#Good').css('display', 'block')
    $('#Good').html('Success! Sending information and redirecting...')
  },
  error: function(jqXHR, textStatus, err) {
    //server error
    console.log("bad server");
  }
});

2 个答案:

答案 0 :(得分:1)

添加contentType应该允许node.js解析布尔值:

$.ajax({
  type: "POST",
  url: "url",
  contentType: "application/json",
  timeout: 2000,
  data: {
    'bool': $('input[name=bool]').is(':checked')
  },
  success: function(data) {
    $('#Error').css('display', 'none')
    $('#Error').html('')
    $('#Good').css('display', 'block')
    $('#Good').html('Success! Sending information and redirecting...')
  },
  error: function(jqXHR, textStatus, err) {
    //server error
    console.log("bad server");
  }
});

答案 1 :(得分:0)

解决了这个问题,因为有些人说我需要将string转换为boolean服务器端。我通过var BoolName = (BoolName == bool);实现了这个目标。现在,这会将MongoDB保存为boolean类型。