繁体   English   中英

如何在不使用jQuery的情况下将Ajax响应文本与某些字符串进行比较

[英]how to compare ajax response text with some string without jQuery

如果它在数据库中发现值发送/回显结果值,但确实找到了发回/回显“ not_found”,我试图通过它取回值。

当我尝试在以下脚本中进行比较时,if总是放在里面,而从不转到其他地方。

我也尝试过NULL,而FALSE代替not_found不起作用。

function showHint(str) {
    var xmlhttp;
    var url=  "check_album.php?q="+str;
    document.getElementById("txtHint1").innerHTML=(url);
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            if(xmlhttp.readyState.responseText !='not_found') {
                document.getElementById("txtHint2").innerHTML=xmlhttp.responseText;
            } else {
                document.getElementById("txtHint3").innerHTML='no result';}
            }
        }
        xmlhttp.open("GET",url,true);
        xmlhttp.send();
    }
}

这是check_album.php代码,它将结果发送回去

    require_once('../php/classes/class.add_album.php');
    if ($_SERVER["REQUEST_METHOD"] == "GET") {
       $album_name = $_GET["q"];

      //make new object
      $objfile = new add_album();

      //call object method with post method value we got and save result in result 
      $file_found=$objfile->find_album($album_name);

      if ($file_found)echo $file_found;
      else         echo 'not_found';
     }

尝试这个。

 if(xmlhttp.responseText !='not_found' ){
        document.getElementById("txtHint2").innerHTML=xmlhttp.responseText;
  } else
  {
        document.getElementById("txtHint3").innerHTML='no result';
  }

这是因为响应文本可能有多余的空格尝试修剪该响应

String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
};

if(xmlhttp.responseText.trim() !='not_found' ){
    document.getElementById("txtHint2").innerHTML=xmlhttp.responseText;
}else{
    document.getElementById("txtHint3").innerHTML='no result';
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM