从 $.post 发送的“true”值未在后端考虑
"true" value sent from $.post not being considered in the back-end
我正在为一个处理真/假/空值的问题挠头,我尝试了几种变体,包括类型强制、假、空等。
基本上,当我点击某人的个人资料图片时,这发生在前端:
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 正文,但这在当今非常容易。
相关文章:
- 未能从后端触发javascript
- 对于loop.if-仅在经过所有间隔后返回true
- 检查浏览器'在asp.net的后端代码中启用或禁用了s JS
- Ajax登录技术(后端php)
- 将Rails后端添加到JS/HTML/CSS应用程序时,正确的文件位置是什么
- 视图没有't在模拟后端时加载
- 是否可以在不使用外部后端的情况下编写grafana数据源插件
- 如何将Angular 2用于各种网站&使用PHP作为后端的模块
- 如何在不重新加载URL的情况下查询Node.Js的后端并更新页面
- 从后端检查Open Social小工具中的用户身份验证
- 如何使用python后端和web前端提供braintree客户端令牌
- 某些Magento后端管理按钮已停止工作
- 构建一个HTML小部件来嵌入付费内容-如何确保与后端的通信安全
- 为什么Express.js后端的CORS设置不起作用
- 调用后端、多路径变量、Ext Js
- 如何断言后端端点已被调用
- 骨干关系是否需要后端
- 与带下划线的后端同步时,转换为 CamelCase 以在 JavaScript 中使用
- 使用 Node 后端设置 webpack 热开发服务器以进行生产
- 从 $.post 发送的“true”值未在后端考虑