我正在使用以下代码来使用php的返回
if (isset($_POST['P_Id'])) {
if (!isset($_SESSION['carted_products'])) {
$_SESSION['carted_products'] = array();
}//end if not set products array in session
if (!in_array($_POST['P_Id'], $_SESSION['carted_products'])) {
array_push($_SESSION['carted_products'], $_POST['P_Id']);
echo "success";
}//end if not in array
else {
echo "already_added";
}
}//end if not set post value
else {
echo "fail";
}//end else
现在在调用页面的jquery部分。我用
$.post(
"add_to_cart.php",
{P_Id:"<?php echo $row['P_Id'] ?>"},
function(responseText){
//if(responseText === "success"){
//things to do on success
}
但if不会返回true。
现在当我在responseText中检查“already_added”的索引时,它返回6 ..
为什么会这样。
答案 0 :(得分:0)
您的回复中可能有空格,请尝试修剪它。
if($.trim(responseText) === "success"){
答案 1 :(得分:0)
在php中尝试echo'0'等等。 在JS AJAX上取得成功,做到了 ....
function(response) {
if(response == 0) { //fail }
if(response == 1) { //success }
}
答案 2 :(得分:0)
你可能在php端回应了一些其他文本(<?php
之前的空白。要了解真正发生的事情,你应该使用像firebug或chrome dev工具这样的客户端控制台并执行{在console.log(responseText);
成功回拨
答案 3 :(得分:0)
嗯,只是快速浏览一下,我看到你没有关闭你的jquery帖子,你的回声后没有分号。
$.post("add_to_cart.php",{P_Id:"<?php echo $row['P_Id']; ?>"},function(responseText){
if(responseText === "success"){
//things to do on success
}
});
答案 4 :(得分:-1)
我个人强烈建议以JSON格式传输数据。我认为这将更安全,更无错误。