JavaScript仅在调用alert()时有效

时间:2019-06-05 09:38:52

标签: javascript ajax

我正在尝试向Java方法发送POST请求,该方法在数据库中创建具有给定表单参数的帐户。 如果成功创建了该帐户,则该方法返回true,然后应该重定向到链接。但是,除非有alert("")函数,否则下面的代码将不起作用。

我认为它与异步模式有关,但是我是JavasScript的新手,非常感谢您的帮助:)

代码如下:

function createAccount(){

var xhr = new XMLHttpRequest();

var fname = document.getElementById("fname").value;
var surname = document.getElementById("surname").value;
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
var rpassword = document.getElementById("rpassword").value;
var emp_no = document.getElementById("emp_no").value;

xhr.open('POST','http://localhost:8080/di24_app/di24/create',true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhr.send('fname='+fname+'&surname='+surname+'&email='+email+'&password='+password+'&rpassword='+rpassword+'&emp_no='+emp_no);
xhr.onreadystatechange = function(){
    if(this.readyState == 4 && this.status == 200) {
        if(this.responseText == "false"){
            document.getElementById("result").innerHTML = "Error creating account!";
            document.getElementById("result").style.textAlign = "center";
        }
        else if(this.responseText == "true"){
            window.location.href = "http://localhost:8080/di24_app/html/home_page/home.html";
        }
    }

}
alert("");
}

2 个答案:

答案 0 :(得分:0)

您可以在如下的onreadystatechange函数中使用回调方法;

function createAccount(successCallback, errorCallback) {
   ...

   xhr.onreadystatechange = function(){
    if(this.readyState == 4 && this.status == 200) {
        if(this.responseText == "false"){
           errorCallback();
        }
        else if(this.responseText == "true"){
           successCallback();
        }
    }
  }
}

然后您可以使用以下两个函数参数调用createAccount方法;

createAccount(
   function () { console.log('success') },
   function () { console.log('error') }
)

您可以将dom操作代码写入这些回调函数中。

答案 1 :(得分:0)

问题是您有一个类型为{submit“的按钮,并且onclick="createAccount()"位于<form/>内,浏览器将自动发布数据并刷新页面,单击该按钮后,函数createAccount()的执行将永远不会结束。

在html button标记上执行以下操作: <button type ="submit" onclick="return createAccount()">Create</button>return之前添加createAccount()

在函数createAccount()的最后添加return false

从“提交类型”按钮调用方法时返回false,将指示浏览器不会自动发布表单数据。

function createAccount(){

....

xhr.onreadystatechange = function(){
    if(this.readyState == 4 && this.status == 200) {
        if(this.responseText == "false"){
            document.getElementById("result").innerHTML = "Error creating account!";
            document.getElementById("result").style.textAlign = "center";
        }
        else if(this.responseText == "true"){
            window.location.href = "http://localhost:8080/di24_app/html/home_page/home.html";
        }
    }

}
//alert("");
return false; // important
}