php 在 jQuery ajax 数据中发送一个布尔值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14716730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Send a boolean value in jQuery ajax data
提问by Don P
I'm sending some data in an Ajax call. One of the values is a boolean set to FALSE. It is always evaluated as TRUE in the PHP script called by the Ajax. Any ideas?
我在 Ajax 调用中发送一些数据。其中一个值是设置为 FALSE 的布尔值。在 Ajax 调用的 PHP 脚本中,它总是被评估为 TRUE。有任何想法吗?
$.ajax({
type: "POST",
data: {photo_id: photo_id,
vote: 1,
undo_vote: false}, // This is the important boolean!
url: "../../build/ajaxes/vote.php",
success: function(data){
console.log(data);
}
});
In vote.php, the script that is called in the above Ajax, I check the boolean value:
在上面Ajax中调用的脚本vote.php中,我检查了布尔值:
if ($_POST['undo_vote'] == true) {
Photo::undo_vote($_POST['photo_id']);
} else {
Photo::vote($_POST['photo_id'], $_POST['vote']);
}
But the $_POST['undo_vote'] == truecondition is ALWAYS met.
但$_POST['undo_vote'] == true条件总是满足。
回答by Jeff Davis
A post is just text, and text will evaluate as true in php. A quick fix would be to send a zero instead of false. You could also put quotes around your true in PHP.
帖子只是文本,文本在 php 中将评估为 true。一个快速的解决方法是发送一个零而不是错误。您也可以在 PHP 中用引号将 true 括起来。
if ($_POST['undo_vote'] == "true") {
Photo::undo_vote($_POST['photo_id']);
} else {
Photo::vote($_POST['photo_id'], $_POST['vote']);
}
Then you can pass in true/false text. If that's what you prefer.
然后你可以传入真/假文本。如果那是你喜欢的。
回答by Ihor Smirnov
You can use JSON.stringify() to send request data:
您可以使用 JSON.stringify() 发送请求数据:
data : JSON.stringify(json)
data : JSON.stringify(json)
and decode it on server:
并在服务器上解码:
$data = json_decode($_POST);
$data = json_decode($_POST);
回答by SGAmpere
You can use 0 and 1 for undo_vote and type cast it in php:
您可以将 0 和 1 用于 undo_vote 并在 php 中键入:
JS side:
JS方面:
undo_vote: 0 // false
Server side:
服务器端:
$undovote = (bool) $_POST['undo_vote']; // now you have Boolean true / false
if($undovote) {
// True, do something
} else {
// False, do something else
}

