通过 AJAX 发布的布尔变量在服务器端被视为字符串

2022-01-19 00:00:00 boolean jquery php ajax post-processing

以下是将类和包添加到会话购物车的 AJAX 功能的一部分:-

Following is a part of an AJAX functionality to add classes and packs to session cart:-

jquery 部分

function addClassToCart(itemId)
{
   addItemToCart(itemId,true);
}

function addPackToCart(itemId)
{
   addItemToCart(itemId,false);
}

function addItemToCart(itemId,isClass)
{   
     $.post(url+"/ajax/add_cart", { operation: 'add_cart','isClass':isClass, 'itemId': itemId},
        function(data)
        {
               if(data.success)
               {
                      alert("item added to cart");
               }
        }, "json");

}

AJAX请求处理php部分-

//Checking operation and other posted parameters
if($_POST['isClass'])
{
  //Code to add class to session cart

}
else
{
  //Code to add pack to session cart
}

奇怪的事

无论我是否传递真/假(通过调用 addClassToCart() 和 addPackToCart()),总是执行将类添加到会话购物车的代码.
如果我像这样将 echo 语句放在那里:-

No matter whether I pass true/false (by calling addClassToCart() and addPackToCart()), always the code to add class to session cart executes.
If I put echo statements there like this:-

    if($_POST['isClass'])
    {
      echo "see if condition ".$_POST['isClass'];
    }
    else
    {
      echo "see else condition ".$_POST['isClass'];
    }

这是输出:-

addClassToCart() 查看条件是否为真
addPackToCart() 判断条件是否为假

addClassToCart() see if condition true
addPackToCart() see if condition false

在 jquery 代码中加入这样的条件可以正常工作:-

Putting conditions like this in the jquery code however works fine:-

function addItemToCart(itemId,isClass)
 {  
     if(isClass)
        alert("is class");
     else
        alert("is pack");
 }

最后,如果我将服务器端代码更改为:-

Finally, if I alter the server side code to this:-

if($_POST['isClass'] === true)
        {
          echo "see if condition ".$_POST['isClass'];
        }
        else
        {
          echo "see else condition ".$_POST['isClass'];
        }

这些是输出 -

addClassToCart() 查看 else 条件为真
addPackToCart() 查看else条件为假

addClassToCart() see else condition true
addPackToCart() see else condition false

那么,为什么布尔变量在这里被视为字符串呢?我在发布参数时做错了吗?

So, why is the boolean variable treated as a string here? Am I doing something wrong in posting parameters?

谢谢,桑迪潘

推荐答案

你本身并没有做错什么,只是当它发布时,它看起来像这样:

You aren't doing anything wrong per se, it's just that when it gets posted, it looks like this:

operation=add_cart&isClass=true&itemId=1234

PHP 无法判断数据类型是什么,因为它没有被传递,它始终只是一串 POST 数据,因此将其与 "true" 进行比较以进行检查,如下所示:

PHP can't tell what the data type is because it isn't passed, it's always just a string of POST data, so compare it to "true" to do your checks, like this:

if($_POST['isClass'] === "true")
{
  //Code to add class to session cart
}
else
{
  //Code to add pack to session cart
}

相关文章