0

The form always gets submitted. I want to submit it only if data=="available" , i.e ...the php file returned available.

function PostData() {
        var xhr;
        if (window.XMLHttpRequest) {
            xhr = new XMLHttpRequest();
        }
        else if (window.ActiveXObject) {
            xhr = new ActiveXObject("Msxml2.XMLHTTP");
        }
        else {
            throw new Error("Ajax is not supported by this browser");
        }
        var username = document.getElementById("username_input").value;
        xhr.open('POST', 'header/onsubmit_check.php');
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.send("username=" + username);


        xhr.onreadystatechange = function () {
                var data=xhr.responseText.trim();
                document.getElementById('onsubmit_feedback').innerHTML = data;
        }

        if (data=='Available') {
        return true;
        } else {
        return false;
        } 
    }
4

1 回答 1

1

在您的 HTML 中,确保您使用表单作为

<form id="my_form" onsubmit="return PostData()">

对您的 javascript 代码进行一些更改

function PostData() {
        var xhr,data;
        if (window.XMLHttpRequest) {
            xhr = new XMLHttpRequest();
        }
        else if (window.ActiveXObject) {
            xhr = new ActiveXObject("Msxml2.XMLHTTP");
        }
        else {
            throw new Error("Ajax is not supported by this browser");
        }
        var username = document.getElementById("username_input").value;
        xhr.open('POST', 'header/onsubmit_check.php');
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.send("username=" + username);


        xhr.onreadystatechange = function () {
                data=xhr.responseText.trim();
                document.getElementById('onsubmit_feedback').innerHTML = data;
                if (data==='Available'){
                     document.getElementById("my_form").submit();
                }
        }

        return false;

    }

当 ajax 返回所需的值时,该函数始终返回false并提交表单。

于 2013-07-28T04:57:45.493 回答