Ajax的响应与我认为的不一样 [英] Ajax response doesn't equal what I think it should

查看:51
本文介绍了Ajax的响应与我认为的不一样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to call a displayUsers function, if response equals "loggedIn" (response is coming from echo statement in php for ajax request). It always jumps straight to the else statement and doesn't execute displayUsers(). However, when I alert response it displays 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.")

    }

}

推荐答案

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

}

这篇关于Ajax的响应与我认为的不一样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆