0

let's say we have the following ajax:

$.ajax({
    url:'myURL.php',
    data:{
        ac:'do',
        isDoable:false
    }
});

Now at the back end when reading the call data, the isDoable is a string, and trying to cast it as Boolean:

$isDoable = (bool) $_REQUEST['isDoable'];

results in $isDoable always being true, even when sent as false. When I encountered this issue I gave up and simply treated it as a string if($_REQUEST['isDoable'] == 'true')

But I cannot get over it! why is this unexpected behavior, and is there a way around it?

4

1 回答 1

0

由于您没有通过 POST 发送 JSON 数据(可以使用 正确处理json_decode),因此您的字符串"true""false"将始终为 boolean true,因为 PHP 将假定,作为非空字符串,您的 var 应转换为true布尔值。

因此,您应该在您的情况下使用字符串比较。

例如:

$value = (bool)"test"; // whatever value, not empty string
var_dump($value);

是布尔值true

$value = (bool)"";
var_dump($value);

是布尔值false

于 2013-08-20T21:21:24.233 回答