AJAX返回并提交HTML

时间:2018-03-27 13:43:46

标签: javascript html ajax

我正在尝试创建一个表单来注册我的网站,但AJAX没有为onsubmit返回false。这是我的代码:

var c = false;
var h = true;
function hi(g, j, k) {
    if (g == j) {
        h = false;
    }
}
function validateForm() {
    var x = document.forms["hi"]["pass1"].value, v = document.forms["hi"]["pass2"].value, b = document.forms["hi"]["user"].value;
    if (x != v) {
        alert("Passwords must match");
        return c;
    }
    xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var a = this.responseText.split("\n")
            for (var n in a) {
                console.log(a);
                console.log(a[n]);
                console.log(b);
                hi(a[n], b, this.responseText)
                if (a[n] == b) {
                    alert("Username already exists")
                    return c;
                };
            };
        };
    };
    xmlhttp.open("GET", "http://www.ncpcs.com/carter/user.txt", true);
    xmlhttp.send();
    return h;
}`

onsubmitreturn validateForm()

1 个答案:

答案 0 :(得分:0)

这是一种不同的方法

首先,不要在表单上使用onsubmit属性,而是在normal (i.e. type="button") button上使用onclick属性。点击按钮后,它将调用validateForm()功能。

<form name="hi" action="otherPage.html">
    <input type="text" name="user" value="" />
    <input type="password" name="pass1" value="" />
    <input type="password" name="pass2" value="" />
    <button type="button" onclick="validateForm()">Submit</button>
</form>

在功能中,如果出现错误,它只会发出警报。如果一切顺利,它将提交表格。

function validateForm() {
    // use better variable names
    var form = document.forms["hi"],
        pass1 = form["pass1"].value, 
        pass2 = form["pass2"].value, 
        user = form["user"].value;

    if (pass1 != pass2) {
        alert("Passwords must match");
        // this is only used to prevent execution of the rest of the function
        return;
    }

    xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var a = this.responseText.split("\n")
            for (var n in a) {
                console.log(a);
                console.log(a[n]);
                console.log(user);
                //hi(a[n], user, this.responseText)
                if (a[n] == user) {
                    alert("Username already exists")
                    return;
                }
            };
            // at this point, everything went well so submit the form 
            form.submit();
        };
    };
    xmlhttp.open("GET", "http://www.ncpcs.com/carter/user.txt", true);
    xmlhttp.send();
}