调用php代码的html文件中的控制台在执行php代码时显示以下结果:
php处理:调试3:TEST IF:在IF 中
php处理:调试4:false
然而,我希望第一个控制台结果是php processing: debug 3: TEST IF: in ELSE
。例如,根据控制台,似乎执行了if-else语句的错误(if)部分,我不明白为什么(对于这个非常简单的代码)???
有什么建议吗?
Php代码:
//TEST CODE
if($productselected_form[0] == true)
{
$response_array['debug3'] = 'TEST IF: in IF';
}
else
{
$response_array['debug3'] = 'TEST IF: in ELSE';
}
$response_array['debug4'] = $productselected_form[0];
//send the response back
echo json_encode($response_array);
//END TEST CODE
Javascript代码(控制台.登录ajax调用php代码):
console.log("php processing: debug 3: "+msg.debug3);
console.log("php processing: debug 4: "+msg.debug4);
问题是将String值与布尔值进行比较,布尔值的计算结果总是为true。你应该像一样将字符串与字符串进行比较
//TEST CODE
if($productselected_form[0] == 'true')
您的$productselected_form[0]
可能是一个字符串,而不是布尔值。使用==
时,PHP会转换类型,以便进行比较。
我猜你有'false'
,而不是false
。转换为布尔值时,以下字符串为false
:
- "0"
- "(空字符串)
其他的都是true
。所以当你做$productselected_form[0] == true
时,你实际上是在做'false' == true
,它的计算结果是true
。
要将'false'
转换为false
,您可以执行以下操作:
$productselected_form[0] = ($productselected_form[0] === 'true');