普通网友 2015-01-12 08:26
浏览 46

AJAX responseText不匹配

I have an AJAX call:

var ajax = new XMLHttpRequest();
ajax.open("POST", "testing.php", true);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.onreadystatechange = function(){
    if(ajax.readyState == 4 && ajax.status == 200){
        var returnVal = ajax.responseText;

        if(returnVal == "success"){
            // Redirect
        }else{
            // Inform of failure
        }
    }
}
ajax.send("testing=1");

that pairs with the following PHP:

if(isset($_POST["testing"])){
    $formScore = checkForm($db_conx);
    if($formScore == 10){
        echo "success";
        exit();
    }else{
        echo "fail";
        exit();
    }
}

And this works just fine. The form score is "10" when it should be, and the value sent back to the AJAX call is, in fact, "success". At least, if I print out the response text:

$('.output').html(ajax.responseText);

the value in output is " success" - WITH the space preceding the word. I cannot select the space with my cursor, but it is there when I view the HTML for the page.

But, no matter what, the line if(returnVal == "success") always equates to false. I've even tried if(returnVal == " success"), but still false.

This is all the code. I've even tried hard-coding $formScore = 10; to see if that was the issue. Regardless, for some reason the equality always comes out false.

Is there something obvious I'm missing? I've tested this 100 different ways, and still the same result.

  • 写回答

2条回答 默认 最新

  • weixin_33682719 2015-01-12 08:29
    关注

    There is a space somewhere in your PHP file which is causing this issue. Possibly at the start of the file before the <?php.

    To work around this you could trim the response before you use it in the condition:

    if (returnVal.trim() == "success") {
    

    Or alternatively change your PHP to return JSON with the flag as a property, that way whitespace will not be an issue.

    The best solution would obviously be to get rid of the space in your server-side code, however we can't diagnose that problem without seeing your PHP.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀