2017-08-29 69 views
0

服務器的一切工作完好,但只是這個簡單的條件語句不工作出於某種原因。Jquery - Javascript does not執行一個簡單的條件

$(document).ready(function() { 
    $("#logsubmit").click(function() { 
     var username = $("#username").val() 
     var password = $("#pwd").val() 

     $.post("functions/logincheck.php", { 
      username: username, 
      password: password 
     }, function(result) { 
      if (result == "success") { 
       window.location = "/"; 
      } else { 
       alert(result); 
      } 
     }); 
    }); 
}); 

即使被某種原因執行result == successelse聲明。

php的scrippt

<?php 
session_start(); 
include '../connect.php'; 
$username = $_POST['username']; 
$password = $_POST['password']; 

$lgchk = $con->prepare("select uid, pass from userlogin where uname = :uname"); 
$lgchk->bindParam(':uname', $username); 
$lgchk->execute(); 

if ($lgchk->rowCount() > 0) { 
    while ($row = $lgchk->fetch(PDO::FETCH_ASSOC)) { 
     $pass = htmlentities($row['pass']); 
     $id = htmlentities($row['uid']); 
    } 
    if ($password == $pass) { 
     $_SESSION["myid"] = $id; 
     echo "success"; 
    } else { 
     echo "Incorrect Password"; 
    } 
} else { 
    echo "Account Doesnt Exist"; 
} 
?> 
+2

你確定'result' *是*成功嗎? – Script47

+2

然後似乎很明顯'結果'不等於'成功'。你需要調試它的原因。你確定它不是「結果」嗎?試試'result.trim()=='success''。如果這樣的話,我強烈建議你改變你的PHP來返回JSON,以避免空白錯誤,並正確使用布爾值,而不是醜陋的字符串比較。 –

+0

我可以保證你的結果是成功的,因爲在其他警報中,我得到一個警告,說「成功」。 – reevkandari

回答

1

做這樣的事情

$(document).ready(function() { 
 
    $("#logsubmit").click(function() { 
 
    var username = $("#username").val() 
 
    var password = $("#pwd").val() 
 

 
    $.post("functions/logincheck.php", { 
 
     username: username, 
 
     password: password 
 
    }, function(result) { 
 
     var r = result.trim(); 
 
     if (r == "success") { 
 
      window.location = "/"; 
 
     } else { 
 
      alert(result); 
 
     } 
 
    }); 
 
    }); 
 
});

使用trim方法&然後將其分配給其他變量。

希望這會幫助你。

+0

它像一個魅力工作感謝您的幫助....但我仍然無能爲力,爲什麼發生..因爲我沒有返回任何額外的空間從PHP .. – reevkandari