【问题标题】:how to compare ajax response text with some string without jQuery如何在没有jQuery的情况下将ajax响应文本与一些字符串进行比较
【发布时间】:2014-06-04 07:24:35
【问题描述】:

如果它在数据库中找到值发送/回显结果值,我正在尝试取回一个值,它确实找到发回/回显'not_found'。

当我尝试在下面的脚本中进行比较时,它总是进入 if,从不进入 else。

我也试过 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';
     }

【问题讨论】:

  • 这到底是什么意思~xmlhttp.readyState.toString(responseText)?
  • 另外,如果您的应用只是返回 not found 的 404 错误状态,您的应用会更有意义。

标签: javascript php ajax


【解决方案1】:

试试这个。

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

【讨论】:

  • 它对我不起作用我已经添加了发送结果的代码,请检查
  • @palsikh alert(xmlhttp.responseText);给你看?
【解决方案2】:

这是因为响应文本可能包含不需要的空格尝试修剪该响应

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';
}

【讨论】:

  • Rajavel D,我已经从文件中复制粘贴了 'not_found',将其作为 ajax 结果返回,所以没有空格,这就是我使用下划线的原因
  • 我已经添加了生成结果的文件,所以请看一下
  • 尝试在if条件前提醒xmlhttp.responseText并让我们知道数据
猜你喜欢
  • 2013-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-23
  • 1970-01-01
相关资源
最近更新 更多