从 $.post 发送的“true”值未在后端考虑

"true" value sent from $.post not being considered in the back-end

本文关键字:后端 true post      更新时间:2023-09-26

我正在为一个处理真/假/空值的问题挠头,我尝试了几种变体,包括类型强制、假、空等。

基本上,当我点击某人的个人资料图片时,这发生在前端:

var isProfilePhoto = false;
if ( $(this).data('profilephoto') === true ) {
  isProfilePhoto = true;
  photoId = parseInt( $(that).data('photoid') );
}
$.post('/mod', { isProfilePhoto: isProfilePhoto, photoId: photoId },
  function (data) {
    if (data.msg === 'delete pic success') {
      $(that).css({ opacity: 0 });
    } else {
      alert("There was a problem. Please contact the webmaster. ERROR CODE: " + data.msg);
    }
});

在后端,我有一个 if/else 案例来检查它是否是个人资料照片,if 看起来像:

  console.log(req.body.isProfilePhoto); // true
  if (req.body.isProfilePhoto == true) {
    ModModel.deletePhoto(photoId, function () {
      if (userIp !== null) {
        ModModel.banUserIP(userIp, function (response) { if (response === true) { return res.send('delete pic success') } } );
      } else {
        return res.send({msg: 'delete pic success'});
      }
    });
  } else {
    // other stuff
  }

但是,一旦进入后端,它就会转到 else 情况,即使req.body.isProfilePhoto为真,它也会转到 else 情况......

知道吗?

您的代码将使用内容类型application/x-www-form-urlencoded和如下所示的 POST 正文发出 POST 请求:

isProfilePhoto=true&photoId=123

你的服务器以字符串的形式接收它(嗯,一个字节流......(,除非你有代码或一些模块告诉它,否则它无法知道四个字节true应该转换为布尔值,或者三个字节123应该转换为一个数字(很可能你的ORM在某个时候会处理后者, 虽然(。

解决此问题的一种方法是发送 JSON 请求。(在 jQuery 中,您可以通过将"json"作为第 4 个参数传递给 $.post 来实现这一点(。在这样的请求中,内容类型将被application/json,POST正文将如下所示(除了没有空格(:

{ "isProfilePhoto": true,
  "photoId":        123 }

在 JSON 中,true 始终是布尔值,"true"始终是字符串,因此当您的服务器解析它时,它将自动具有正确的类型。当然,您必须更改服务器端代码才能解析 JSON 正文,但这在当今非常容易。