通过发布AJAX布尔变量被视为服务器端串 [英] boolean variables posted through AJAX being treated as strings in server side
问题描述
下面是一个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()),总是code添加类会话车执行。
如果我把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的code然而正常工作: -
Putting conditions like this in the jquery code however works fine:-
function addItemToCart(itemId,isClass)
{
if(isClass)
alert("is class");
else
alert("is pack");
}
最后,如果我改变了服务器端code到这一点: -
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()看别的状况的真实
addPackToCart()看别的条件为假
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?
谢谢, Sandeepan
Thanks, Sandeepan
推荐答案
您没有做错任何事情本身,它只是当它被发布,它看起来是这样的:
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数据只是一个字符串,因此它比作真实
来做你检查,是这样的:
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
}
这篇关于通过发布AJAX布尔变量被视为服务器端串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!