2014-03-14 29 views
0

我試圖調用一個displayUsers函數,如果響應等於「loggedIn」(響應來自PHP中的echo語句對於ajax請求)。它總是直接跳到else語句並且不執行displayUsers()。但是,當我提醒響應時,它會顯示loggedIn。阿賈克斯響應不等於我認爲應該

這裏是我的代碼:

function ajaxRequest(url, method, data, asynch, responseHandler) { 
    var request = new XMLHttpRequest(); 
    request.open(method, url, asynch); 

    if (method == "POST") { 
     request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
    } 
    request.onreadystatechange = function() { 
     if (request.readyState == 4) { 
      if (request.status == 200) { 
       responseHandler(request.responseText); 
      } 
     } 
    } 

    request.send(data); 
} 

//loginCheck 
    function loginCheck() { 
     var username = document.getElementById("usernameLogin").value; 
     var password = document.getElementById("passwordLogin").value; 
     var data="usernameLoginAttempt="+username+"&passwordLoginAttempt="+password; 
     ajaxRequest("../PHP/CODE/login_check.php", "POST", data, true, loginCheckResponse); 
    } 

    function loginCheckResponse(response) { 
    //check response, if it is "loggedIn" then call show users function 
    alert(response); 
    if (response == "loggedIn") { 
     displayUsers(); 
    } else { 
     alert("Login Failed. Please try again.") 

    } 

} 
+0

顯示您的PHP如何返回數據。 – dhidy

+0

你確定字符大小寫是否一致。 嘗試response.toLowerCase()==「已登錄」 –

+0

字符大小寫是否正確。 – user2716814

回答

4
// response is an object which you get from ajex. 
// You have not written how you call loginCheckResponse() 
// call like loginCheckResponse(response.<variable which you return from service page>) 
function loginCheckResponse(response) 
{ 
    //check response, if it is "loggedIn" then call show users function 
    alert(response); 
    if (response == "loggedIn") { 
     displayUsers(); 
    } else { 
     alert("Login Failed. Please try again.") 
    } 

} 
+0

增加了我稱爲loginCheckResponse()的方式。 – user2716814

+1

你可以在ajax中成功調用這個函數並傳遞這個函數中的值,正如我告訴你的迴應<你從服務頁面返回的變量> –

+0

loginCheckResponse()正在調用......問題在於if語句。響應變量等於ajax響應request.responsetext。當我提醒響應它告訴我,request.responsetext等於「loggedIn」,但它不斷跳到else語句,因此缺少displayUsers(); – user2716814

0

改變了我的代碼:

//logged in 
function loginCheckResponse(response) { 

    if(response.trim()=="loggedIn"){ 
     displayUsers(); 
    } 
    else{ 
     alert("Login Failed. Please try again."); 
    } 

} 

現在的作品。無論如何,感謝人們的幫助。