javascript - Ajax 响应不等于我认为应该的

标签 javascript php ajax

如果响应等于“loggedIn”(响应来自 php 中针对 ajax 请求的 echo 语句),我正在尝试调用 displayUsers 函数。它总是直接跳转到 else 语句,并且不执行 displayUsers()。但是,当我提醒响应时,它显示登录。

这是我的代码:

   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.")

    }

}

最佳答案

// 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.")
    }

}

关于javascript - Ajax 响应不等于我认为应该的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22397051/

相关文章:

javascript - AngularJS 在不刷新页面的情况下更改 URL

php - 如何在php中为swagger定义和使用可重用的参数列表

javascript - 在 PHP 和 Ajax 中从数据库数据动态创建下拉列表

c# - 如何将 Collection 传递给模态对话框窗口?

javascript - 防止CKEditor过滤掉 "tel"协议(protocol)

javascript - 为什么 foo() 在 react-native 中输出 2,而 Chrome 控制台输出 3?

php - 我可以更改 Constraint 或 ConstraintValidator 中的值吗?

php - Yii Controller 命名约定

javascript - 等待 Canvas 动画并获取完成

javascript - 在解决 RSVP 之前等待其他交互发生