回调函数返回值

时间:2018-07-24 16:40:20

标签: javascript ajax

如何使用回调函数为表单验证返回值?这对我不起作用。

<form action="loggedin.php" onsubmit="return test(valid)" method="post">

function test(callback) {
    var k = "";
    var httpRequest = new XMLHttpRequest();
    httpRequest.onload = function(){
        k = callback(httpRequest.responseText);
        return k;
    };
    httpRequest.open("POST", "check.php",true);
    var a = document.getElementById("email").value;
    var b = document.getElementById("pwd").value;
    httpRequest.send("email=" + a + "&passwd=" + b);
}

function valid(resp){
    alert(resp);    // resp is correctly defined here
        if(resp == "Correct"){
            return true;
        }
        else{
            return false;
        }
} 

我需要使用ajax响应来验证表单数据。.我想为表单onsubmit方法返回true或false。.回调函数可以返回值吗?

1 个答案:

答案 0 :(得分:0)

AJAX将异步请求发送到所需位置,这意味着此后它独立于程序运行。 AJAX中的回调函数的目的是在返回页面时应用返回到页面的内容,因此它不能将值返回到调用它的原始形式。

您可以采取的减少php文件的方法是将检查文件和登录文件结合在一起,然后清除onsubmit并使其保持常规的HTML表单提交,或者继续使用ajax。

无论哪种方式,都会对您的代码进行更新,以在返回第一个ajax后触发loginin.php

<form action="loggedin.php" onsubmit="return test(valid)" method="post">

function test(callback) {
    var k = "";
    var httpRequest = new XMLHttpRequest();
    httpRequest.onload = function(){
        k = callback(httpRequest.responseText);
        return k;
    };
    httpRequest.open("POST", "check.php",true);
    var a = document.getElementById("email").value;
    var b = document.getElementById("pwd").value;
    httpRequest.send("email=" + a + "&passwd=" + b);
}

function valid(resp){
    alert(resp);    // resp is correctly defined here
        if(resp == "Correct"){
            var httpRequest = new XMLHttpRequest();
            httpRequest.onload = function(){
                // do what needs to be done to the page, like reload
            }
            httpRequest.open("POST", "loggedin.php", true);

            // this is just using the variables from earlier
            var a = document.getElementById("email").value;
            var b = document.getElementById("pwd").value;
            httpRequest.send("email="+ a +"&passwd="+ b);
        }
        else{
            return false;
        }
}