在数组中定义ajax变量和函数,不工作,就绪状态对于非最后一个元素始终为0

时间:2013-08-06 02:44:37

标签: javascript ajax javascript-events

我要开发一个包含许多ajax调用的网站,所以为了方便起见,我将所有ajax变量放在一个关联数组中,通过循环遍历这个数组,我想分配onreadystatechange函数。但这似乎仅适用于ajaxVariables数组的最后一个元素。

如果我取消注册registrationXHR呼叫并注释掉另一个XHR呼叫,我什么也得不到,但它反过来正常。每当readyState为0时,使用registrationXHR。

我正在使用的代码如下。我看不出为什么会发生这种情况的原因。也许ajax电话干扰了。请帮忙。提前谢谢。

<html>
<head>
    <script type="text/javascript">
    var ajaxVariables = {
        registrationXHR: {
            XHRHandle: new XMLHttpRequest(),
            expectedSuccessValue: '1',
            expectedFailureValue: '0',
            successMessage: "Congratulations, you have been successfully registered.",
            errorMessage: "Sorry, registration failed.",
            filename: "thing.txt",
            furtherFunctions: [
                "slideToOnlineVerification"
            ]
        },
        anotherXHR: {
            XHRHandle: new XMLHttpRequest(),
            expectedSuccessValue: '1',
            expectedFailureValue: '0',
            successMessage: "Congratulations, you have been successfully registered.",
            errorMessage: "Sorry, registration failed.",
            filename: "thing.txt",
            furtherFunctions: [
                "slideToOnlineVerification"
            ]
        }
    };
    for (var key in ajaxVariables) {
        ajaxVariables[key].XHRHandle.onreadystatechange = function() {
            if (ajaxVariables[key].XHRHandle.readyState === 4 && ajaxVariables[key].XHRHandle.status === 200) {
                var JSONResponse = JSON.parse(ajaxVariables[key].XHRHandle.responseText);
                if (JSONResponse['response'] === ajaxVariables[key].expectedSuccessValue) {
                    //for (var func in ajaxVariables[key].furtherFunctions) {
                    //    window[ajaxVariables[key].furtherFunctions[func]](JSONResponse);
                    //}
                    alert(ajaxVariables[key].successMessage);
                } else {
                    alert(ajaxVariables[key].errorMessage);
                }
            }
        };
    }
    //ajaxVariables.registrationXHR.XHRHandle.open("GET", "" + ajaxVariables.registrationXHR.filename + "", true);
    //ajaxVariables.registrationXHR.XHRHandle.send();

    ajaxVariables.anotherXHR.XHRHandle.open("GET", "" + ajaxVariables.anotherXHR.filename + "", true);
    ajaxVariables.anotherXHR.XHRHandle.send();
    </script>
</head>
<body>

</body>

0 个答案:

没有答案