2016-07-28 42 views
0

我已經實現與AJAX請求登錄頁面,用戶根據從PHP頁面loginrequest.phpAJAX調用不重定向

$.ajax ({ 

    type: "POST", 
    url: "ajax/loginrequest.php", 
    data: { 
    username: username, 
    password:pass 
    }, 

    dataType: "text", 

    success: function(html){ 

    console.log(html); // Prints 'login' or 'fail' 

    if(html == 'login'){ 
     console.log("Yes"); //Never Printed 
     window.location.href = 'index.php'; 
    } 
    else if(html == 'fail'){ 
     alert("Incorrect Username and/or Password"); 
    } 
    } 
}); 

響應這是loginrequest.php代碼回聲loginfail回重定向在AJAX功能

if($count == 1){ 
    $bool = password_verify($mypassword, $row[1]); 

    if($bool == true){ 
    $_SESSION['user'] = $myusername; 
    $_SESSION['division'] = $row[2]; 
    $return = 'login'; 
    } 
    else{ 
    $return = 'fail'; 
    } 
} 
else{ 
    $return = 'fail'; 
} 
echo $return; 

console.log我的成功函數打印內登錄或取決於憑據失敗,但由於某些原因,如果語句根本不會計算爲真。我的網頁永遠不會重定向,也不會顯示警報。我只是將這些文件上傳到網絡服務器,他們在WAMP上工作良好,但由於某種原因,它不再工作。我在loginrequest.php嘗試json_encode(),但它仍然無法工作。我的數據庫調用沒有任何問題,因爲它根據憑證返回登錄或失敗,只是if語句在成功函數中。

我在這裏做錯了什麼?

+0

可能是一個粘貼錯誤,但在Ajax請求結束時會出現一個雜散的回滴。 – pmahomme

+0

您是否看到實際要出去的請求? (F12,網絡標籤),請求後還有什麼事情發生? – Jakumi

+0

@pmahomme yea它是從這裏粘貼代碼 – ybce

回答

1

很可能你有一個流浪的空白由PHP

被回顯的嘗試

success: function(html){ 

    console.log(html); // Prints 'login' or 'fail' 

    console.log(html.length); // Is it 5 and 4 respectively? 

    html = $.trim(html); // if a space is the issue then this should fix it 

    if(html == 'login'){ 
     console.log("Yes"); //Never Printed 
     window.location.href = 'index.php'; 
    } 
    else if(html == 'fail'){ 
     alert("Incorrect Username and/or Password"); 
    } 
} 
+0

好吧,所以我用'if(html.indexOf(「login」)> = 0)'它工作,所以我猜這是一個空白問題!我會接受你的回答。我會嘗試你的方法以及完整性。 – ybce

+0

@ybce不客氣! – MonkeyZeus

-1

使用真/假值像1/0 ....更可靠

 if(html.trim() == 'login'){ //check and remove whitespace 
     console.log("Yes"); 
      window.location.href = 'index.php'; 
     } 
     else if(html.trim() == 'fail'){ 
      alert("Incorrect Username and/or Password"); 
     } 
+0

我可以知道爲什麼上面的答案是downvoted? – coolstoner