doujiao0110 2010-09-06 21:44
浏览 77
已采纳

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

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

The jquery part

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");

}

The AJAX request processing php part -

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

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

The strange thing

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'];
    }

This is the output:-

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

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'];
        }

These are the outputs -

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?

Thanks, Sandeepan

  • 写回答

4条回答 默认 最新

  • drcj64241 2010-09-06 21:47
    关注

    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 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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line