为什么后续调用我的函数不会按预期更新元素的可见性?

时间:2014-01-02 17:22:36

标签: javascript html

我正在添加一些表单验证并使用以下命令更新通知的可见性,具体取决于http请求的状态代码:

function isValidEndpoint()
{
    var xmlHttp = null;
    var myurl = "/restyendpoint/" + document.getElementById("endpoint").value;
    xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", myurl, true );
    xmlHttp.send( null );
    if (xmlHttp.status == 409) {
        document.getElementById("sucnot").style.visibility="hidden";
        document.getElementById("warnot").style.visibility="visible";
    } else {
        document.getElementById("sucnot").style.visibility="visible";
        document.getElementById("warnot").style.visibility="hidden";
    }
}

当我加载页面时,元素都是不可见的,在键入第一个字符时,我得到“无端点”消息(因为输入的第一个字符在数据库中不存在)。从那时起,即使我可以通过“restyendpoint”验证确认正确的请求/响应,通知的可见性也不会改变。

1 个答案:

答案 0 :(得分:0)

由@Musa提供Prior art。我修改了我的代码如下,它现在有效:

function isValidEndpoint()
{
    var xmlHttp = null;
    var myurl = "/restyendpoint/" + document.getElementById("endpoint").value;
    xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function(){
        if (xmlHttp.readyState === 4) {// request is done
            if (xmlHttp.status === 409) {// endpoint exists
                document.getElementById("sucnot").style.visibility="collapse";
                document.getElementById("warnot").style.visibility="visible";
            } else {//endpoint doesn't exist
                document.getElementById("sucnot").style.visibility="visible";
                document.getElementById("warnot").style.visibility="collapse";
            }
        }
    };
    xmlHttp.open( "GET", myurl, true );
    xmlHttp.send( null );
}

因此,在请求中将async设置为true,xmlHttp对象需要在返回时检查状态。它正在做的是立即检查状态,并默认为始终显示特定通知。