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

如何将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"
    
    点赞 评论

相关推荐 更多相似问题