Javascript / AJAX发送多个返回

时间:2016-01-05 18:09:56

标签: javascript jquery ajax

我正在尝试在用户输入他/她的凭据并验证凭据后替换表行。这是对servlet的简单AJAX调用,发送凭据并返回一些特定信息(名字,姓氏,邮政编码等)。

我注意到对authenticate的调用实际上会多次返回,第一对是null并且是“undefined”。我放了一些代码来处理这个问题,然后删除了我所有的故障排除警报,发现它根本没用。

在authenticate()返回到位之前的警报,它按照我的意图工作。但是,如果我取消警报,它就会停止工作。

我没有那么多使用AJAX,也无法定义足够的问题来在线进行任何研究。我希望尽管我没有尝试描述这个问题,但有人会认出我的问题。

那么,我在哪里错了?

HTML:

<!DOCTYPE html>
<html>
<head>
    <title>Training Daily Activity Report</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="stylesheets/dar.css">
    <script src="js/DAR.js"></script>
    <script src="js/jquery-1.10.2.min.js"></script>
    <style type='text/css'>
        html { 
            background: url(images/officebuilding.jpg) no-repeat center center fixed; 
            -webkit-background-size: cover;
            -moz-background-size: cover;
            -o-background-size: cover;
            background-size: cover;
        }
    </style>
</head>
<body>
    <div style='width: 100%;text-align: center;margin-top: 55px;'>
        <div style='width: 90%;margin-right: auto; margin-left: auto;'>
            <form id='fmDAR' action='DARServlet' method='post'>
                <input type="hidden" id="formType" name="formType" value="" />
            </form>
            <table style='width: 100%'>
                <tr>
                    <td colspan='2' class='firstBlock'>
                        <span style='font-size: 24px'>Daily Activity Report</span>
                    </td>
                </tr>
                <tr>
                    <td style='width: 15%;text-align: right;'>
                        <span style='padding-right: 5px;'>Categories worked on:</span>
                    </td>
                    <td style='width: 75%;'>
                        <textarea rows='3' style='width: 99%;' type='text' id='taCategories' name='taCategories' value=''></textarea>
                    </td>
                </tr>
            </table>
            <br>
            <table style='width: 100%;'>
                <tr>
                    <td class="secondBlock">
                        <span>Trainee</span>
                    </td>
                    <td class="secondBlock">
                        <span>DTO/Trainer</span>
                    </td>
                    <td class="secondBlock">
                        <span>Phase</span>
                    </td>
                    <td class="secondBlock">
                        <span>DOT</span>
                    </td>
                </tr>
                <tr>
                    <td style='text-align: center;'>
                        <input style="width: 98%;" type="text" id="txtTrainee" name="txtTrainee" value="" />
                    </td>
                    <td style='text-align: center;'>
                        <input style='width: 98%;' type="text" id="txtTrainee" name="txtTrainee" value="" />
                    </td>
                    <td style='text-align: center;'>
                        <input style='width: 98%;' type="text" id="txtTrainee" name="txtTrainee" value="" />
                    </td>
                    <td style='text-align: center;'>
                        <input style='width: 98%;' type="text" id="txtTrainee" name="txtTrainee" value="" />
                    </td>
                </tr>
            </table>
            <br>
            <table style='width: 100%;'>
                <tr>
                    <td class='thirdBlock'>
                        Trainee's Comments:  What did you learn?  What do you still need to know?
                    </td>
                </tr>
                <tr>
                    <td style='width: 100%;'>
                        <textarea style='width: 99%;' rows='8' id='taTraineeComments' name='taTraineeComments' value=''></textarea>
                    </td>
                </tr>
            </table>
            <br>
            <table style='width: 100%;'>
                <tr>
                    <td class='fourthBlock'>
                        DTO Comments:  What areas of trainee performance need improvement?
                    </td>
                </tr>
                <tr>
                    <td style='width: 100%;'>
                        <textarea style='width: 99%;' rows='8' id='taDTOComments' name='taDTOComments' value=''></textarea>
                    </td>
                </tr>
            </table>
            <br>
            <table style='width: 100%;'>
                <thead>
                    <tr>
                        <td>&nbsp;</td>
                        <td>Logon ID</td>
                        <td>Password</td>
                        <td>&nbsp;</td>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td class='authentication' id='tdTraineeAuthentication'>
                            Trainee Authentication:
                        </td>
                        <td>
                            <input type='text' id='txtTraineeAuthLogon' name='txtTraineeAuthLogon' value='' />
                        </td>
                        <td>
                            <input type='password' id='txtTraineeAuthPW' name='txtTraineeAuthPW' value='' />
                        </td>
                        <td>
                            <button onclick='authenticateUser()'>Authenticate</button>
                        </td>
                    </tr>
                    <tr>
                        <td class='authentication'>
                            DTO Authentication:
                        </td>
                        <td>
                            <input type='text' id='txtDTOAuthLogon' name='txtDTOAuthLogon' value='' />
                        </td>
                        <td>
                            <input type='password' id='txtDTOAuthPW' name='txtDTOAuthPW' value='' />
                        </td>
                        <td>
                            <button onclick='authenticateDTO()'>Authenticate</button>
                        </td>
                    </tr>
                    <tr>
                        <td class='authentication'>
                            DTS Authentication:
                        </td>
                        <td>
                            <input type='text' id='txtDTSAuthLogon' name='txtDTSAuthLogon' value='' />
                        </td>
                        <td>
                            <input type='password' id='txtDTSAuthPW' name='txtDTSAuthPW' value='' />
                        </td>
                        <td>
                            <button onclick='authenticateDTS()'>Authenticate</button>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
        <div style='text-align: center;margin-top: 20px;'>
            <button style='height: 45px;' id='btnSave' onclick='saveDAR()'>Save Daily Activity Report</button>
        </div>
    </div>

</body>

JS:

function authenticateUser() {
    var logon = document.getElementById("txtTraineeAuthLogon").value;
    var pw = document.getElementById("txtTraineeAuthPW").value;
    if (logon != null && pw != null) {
        var tmp = authenticate(logon, pw);
        var tmp2;
        if (tmp != null) { //authenticate returns several results, the first few being "null" or "undefined"
            if (tmp.toLowerCase() != 'undefined') {
                tmp2 = tmp;
            }
        }
        if (tmp2 != null) {
            var tmpRow = "                    <tr>"
                    + "                        <td class='authentication' id='trTraineeAuthentication'>"
                    + "                            Trainee Authentication:"
                    + "                        </td>"
                    + "                        <td colspan='3' style=\"text-align: center;\">"
                    + "                            Authenticated as " + tmp2 + ""
                    + "                        </td>"
                    + "                    </tr>";
            $("td#tdTraineeAuthentication").parent().replaceWith(tmpRow);
        }
    }
}
function authenticateDTO() {
}
function authenticateDTS() {
}
function authenticate(logon, password) {
    var returnString = null;
    var givenName;
    var sn;
    var postalCode;
    $.ajax({
        url: 'DARServlet',
        data: {
            formType: 'authenticate', logon: logon, password: password
        },
        contentType: 'application/json',
        mimeType: 'application/json',
        success: function (responseText) {
            $.each(responseText, function (key, value) {
                if (key == "givenName") {
                    givenName = value;
                } else if (key == "sn") {
                    sn = value;
                } else if (key == "postalCode") {
                    postalCode = value;
                }
            });
            returnString = givenName + " " + sn + ", Employee #: " + postalCode;
            //alert(returnString);
        },
        error: function (request, status, error) {
            alert("The credentials used cannot be authenticated.  Please re-enter and try again.");
            return null;
        }
    });
    alert("returnString: " + returnString);
    return returnString;
}

2 个答案:

答案 0 :(得分:1)

Authenticate方法是异步的,现在它将返回null。您必须将回调函数传递给authenticate并在success处理程序中调用它,或者返回DefferedPromise并像这样使用

authenticate(logon, password).then(function(returnString) {
  // your logic 
});

答案 1 :(得分:1)

ajax对象的query = Foo.objects.filter( bar__bbb=True ).distinct() aaa_sum = query.aggregate(models.Sum("aaa", distinct=True))['aaa__sum'] success属性是最终将执行的函数。请记住,AJAX中的A最初代表异步,因此您的成功/错误函数不会在与进行AJAX调用的函数相同的范围内运行。

你可以跳过各种各样的箍,试图用返回值的概念制作异步代码网格,但这种方式就是疯狂。如果您向前移动逻辑,您将获得更多运气,因此您可以在成功/错误函数中做出决策。

它是一种不同的编程思维方式,但您不想说error,而是需要if(authenticate()){ do something;}的同步返回值,而是要遵循{{1}这样的模式}(其中authenticate()是一个函数名),在执行链中传递你的逻辑。

有关在JavaScript中更好地处理异步逻辑的方法的更多示例,您可以搜索JavaScript&#34; promise&#34;。