微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – if(条件在jascript中失败)

我有以下代码Windows中的localhost中工作.但在服务器中相同的代码失败.

即使data == found,也是if条件没有被执行写入;我检查了找到的返回数据值,但无法弄清楚代码没有正确执行的原因

function checkAvailability() {
  $("#loaderIcon").show();
  jQuery.ajax({
    url: "ajaxcheck.PHP",
    data:'tran_id='+$("#tran_id").val(),
    type: "POST",
    success:function(data){
      console.log(data);
      //var x=data;
      $("#loaderIcon").hide();
      //console.log((data=="found"));
      if(data=="found")
      {
        $("#singlebutton").prop('disabled', false);
        console.log("fail");
        $("#tran_id-status").html("Found");
      }
      else
      {
        console.log(data);
        $("#singlebutton").prop('disabled', true);
        $("#tran_id-status").html("");  
        console.log("ss");
      }
    },
    error:function (){}
  });
}

这是ajaxcheck.PHP

<?PHP
require_once("dbcontroller.PHP");
$db_handle = new DBController();
$space=" ";

if(!empty($_POST["tran_id"])) {
  $result = MysqL_query("SELECT count(*) FROM bank WHERE tran_id ='" . $space.$_POST["tran_id"] . "'");
  $row = MysqL_fetch_row($result);
  $user_count = $row[0];
  if($user_count>0) {
     // echo "<span class='status-not-available' id=\"stat\"name=\"stat\" value=\"ok\"> Transaction Details Found.</span>";
    echo"found";
  }else{
      //echo "<span class='status-available' id = \"stat\" name =\"stat\"value=\"not\"> (Enter Valid transaction id to submit)</span>";
      echo"notfound";
  }
}
?>

解决方法:

问题是您的数据变量将返回一个新的行字符.这有两种解决方案1.修剪返回值. 2.弄清楚为什么PHP正在服务新线路.

解决方案1:

if(data.trim()=="found")

这使用JS修剪功能,https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim.

解决方案2:

尝试删除?>从PHP文件的末尾开始(PHP文件仍然有效).这样,如果在它之后有额外的行,它们将不会作为输出,JS将不会收到它们.

从手册:

If a file is pure PHP code, it is preferable to omit the PHP closing tag at the end of the file. This prevents accidental whitespace or new lines being added after the PHP closing tag, which may cause unwanted effects because PHP will start output buffering when there is no intention from the programmer to send any output at that point in the script.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐