doutenglou6588 2018-12-28 22:03 采纳率: 0%
浏览 192
已采纳

如何将ajax responseText设置为等于string?

I have a problem with ajax.responseText in condition where it has to be equal to string which is passed in from php echo from external file, the thing is that the string seems not to be equal to ajax.responseText,

but if alert(ajax.responseText) it is exactly the string "friend_request_sent"

function friendToggle(type,user,elem){
var conf = confirm("Press OK to confirm the '"+type+"' action for user <?php echo $u; ?>.");

if(conf != true){
    return false;
}   
_(elem).innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "friend_system.php");

ajax.onreadystatechange = function() {
    if(ajaxReturn(ajax) == true) {

        if(ajax.responseText=="friend_request_sent"){          
            _(elem).innerHTML = 'OK Friend Request Sent';       
        } else if(ajax.responseText == "unfriend_ok"){
            _(elem).innerHTML = '<button onclick="friendToggle(\'friend\',\'<?php echo $u; ?>\',\'friendBtn\')">Request As Friend</button>';       
        } else{        
            alert(ajax.responseText);
            _(elem).innerHTML = 'Try again later';
        }
    }
}
ajax.send("type="+type+"&user="+user);

}

now the code im getting from friend_system.php

 ...{ 
 echo"friend_request_sent";
 exit();
 }

and the ajax js code

function ajaxObj( meth, url ) {
 var x = new XMLHttpRequest();
 x.open( meth, url, true );
 x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 return x;
}
function ajaxReturn(x){
   if(x.readyState == 4 && x.status == 200){
    return true;    
 }

} the third condition is where it struggles ,it always goes to else, why?

  • 写回答

1条回答 默认 最新

  • dsrnwngq411594 2018-12-28 22:29
    关注

    To check ajax response against any string, it is better to trim the response text

    request.responseText.trim() === "string"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探