普通网友 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 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝