【问题标题】:jquery ajax call returning more than a single wordjquery ajax 调用返回多个单词
【发布时间】:2013-05-15 03:21:09
【问题描述】:

我正在使用以下代码来使用 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..

为什么会这样。

【问题讨论】:

  • 您可以尝试将exit();return; 放在您的echo 语句之后吗?

标签: php jquery ajax post


【解决方案1】:

您的回复中可能有空格,请尝试修剪它。

if($.trim(responseText) === "success"){

【讨论】:

    【解决方案2】:

    在 php 中尝试 echo '0' 等等。 在 JS AJAX 上成功,做 ....

    function(response) {
      if(response == 0) { //fail }
      if(response == 1) { //success }
    }
    

    【讨论】:

      【解决方案3】:

      您可能在 php 端回显了一些其他文本(&lt;?php 之前的空格。要了解实际发生的情况,您应该使用像 firebug 或 chrome 开发工具这样的客户端控制台并执行 console.log(responseText);.$post 成功回调中的 if 之前

      【讨论】:

        【解决方案4】:

        好吧,快速浏览一下,我发现你没有关闭你的 jquery 帖子,并且你的 echo 后面没有分号。

        $.post("add_to_cart.php",{P_Id:"<?php echo $row['P_Id']; ?>"},function(responseText){
            if(responseText === "success"){
                //things to do on success
            }
        });
        

        【讨论】:

          【解决方案5】:

          我个人强烈建议以 JOSN 格式传输数据。我认为这样会更安全且不会出错。

          【讨论】:

            猜你喜欢
            • 2011-05-21
            • 1970-01-01
            • 1970-01-01
            • 2011-02-20
            • 2011-09-21
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多