JavaScript仅在调用alert()时工作
我试图向一个Java方法发送一个JavaScript仅在调用alert()时工作,javascript,ajax,Javascript,Ajax,我试图向一个Java方法发送一个POST请求,该方法在数据库中创建一个具有给定表单参数的帐户。 如果成功创建帐户,该方法将返回true,然后我将被重定向到链接。但是,除非有警报(“”函数,否则下面的代码不起作用 我假设它与异步模式有关,但我对JavasScript不熟悉,非常感谢您的帮助:) 代码如下: function createAccount(){ var xhr = new XMLHttpRequest(); var fname = document.getElementById("
POST
请求,该方法在数据库中创建一个具有给定表单参数的帐户。
如果成功创建帐户,该方法将返回true,然后我将被重定向到链接。但是,除非有警报(“”
函数,否则下面的代码不起作用
我假设它与异步模式有关,但我对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("");
}
您可以在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();
}
}
}
}
然后可以使用以下两个函数参数调用CreateCount方法
createAccount(
function () { console.log('success') },
function () { console.log('error') }
)
您可以将dom操作代码写入这些回调函数。问题是您有一个type=“submit”按钮,并且
onclick=“createAccount()”
在
中,浏览器将自动发布数据并刷新页面,单击该按钮后,因此,函数createAccount()
的执行永远不会结束
在html按钮标记上执行以下操作:
创建
在createAccount()之前添加return
在函数createAccount()的末尾添加返回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
}
能否显示调用createAccount()
的位置和方式?调用函数后,如果没有alert(),控制台中是否存在任何错误?我目前不知道这是如何工作的,因为document.getElementsById不存在。您不能通过Id获取多个元素,因为Id应该是唯一的。创建这是我调用函数的方式。您是否仅在设置了xhr.onreadystatechange
之后才尝试调用xhr.send()
?当前,您在创建dom时直接调用函数。您必须编写onClick=“createAccount”,而不是onClick=“createAccount()”。这样您就不会直接调用它,onclick属性应该只在通过回调时获取函数引用。很好,没问题:)