如何根据从php文件收到的数据为ajax表单提交返回true或false?

时间:2013-07-28 04:46:42

标签: php ajax

表单始终会被提交。我只想在data ==“available”时提交它,即...返回的php文件可用。

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;
        } 
    }

1 个答案:

答案 0 :(得分: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;

    }

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