通过Ajax将布尔人转换为字符串的PHP



我正在使用ajax发送类似的东西:

var details = [{name: "thing1", value: true}, {name: "thing2", value: true}, {name: "thing3", value: false}]
$.ajax({
    url: 'myphp.php',
    type: 'POST',
    dataType: 'JSON',
    data: {
        universalDetails: details,
    },
//...etc.

在我的php中,如果我包括在内:

$universalDetails = $_POST["universalDetails"];
var_dump($universalDetails);

我的所有value s在数组中显示为字符串...像这样:

{ ["name"]=> string(20) "thing1" ["value"]=> string(4) "true" }

这里发生了什么?我如何将其保存为布尔人?

是设计,因为每个帖子/获取参数基本上都是字符串。您可以尝试执行if($_POST['universalDetails']['value'] == 'true') ...,因为PHP会将字符串"true"更改为具有true值的布尔值(不是字符串!):

更多信息:https://secure.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting

但是请注意:var_dump((bool) "false"); // bool(true)

最新更新