Javascript Don';不允许表单提交,而是发送xmlHttpRequest
下面是我的代码,只是表单提交上发送xmlhttprequest的一个简单事件Javascript Don';不允许表单提交,而是发送xmlHttpRequest,javascript,Javascript,下面是我的代码,只是表单提交上发送xmlhttprequest的一个简单事件 <form action="http://localhost/cn/account_test/index.php" method="post" onsubmit="login(this);"> <label>Username</label><br> <input type="text" id="username" name="username">
<form action="http://localhost/cn/account_test/index.php" method="post" onsubmit="login(this);">
<label>Username</label><br>
<input type="text" id="username" name="username"><br>
<label>Password</label><br>
<input type="password" id="password" name="password">
<br>
<button>Submit</button>
</form>
但是return false或e.preventDefault()都不起作用。是否有任何帮助,请提供意见?
此
是对表单对象的引用,它没有preventDefault
方法。在登录
功能中传递事件
:
<form action="http://localhost/cn/account_test/index.php" method="post" onsubmit="login(event);">
...
</form>
...
您的代码中有两件事:
Submit
缺少类型属性:提交
login(this)
函数中的this
没有属性preventDefault
。它指的是表单
元素document.getElementById(“myForm”).addEventListener(“提交”,登录);
功能登录(e){
e、 预防默认值();
console.log('catch!');
//这里有更多的代码。。。
}
用户名
密码
提交
使用结束
document.querySelector('#form').addEventListener('click',function(e){
e.preventDefault();
});
thx对于帮助,它是有效的。您应该使用JavaScript设置事件侦听器,而不是使用内联JavaScript 步骤1:删除内联JS并向表单中添加ID:
<form action="http://localhost/cn/account_test/index.php" method="post" id="form">
尝试onsubmit=“返回登录(this);”
尝试提交
<form action="http://localhost/cn/account_test/index.php" method="post" id="form">
document.getElementById("form").addEventListener("submit", function(e) {
e.preventDefault();
var $data = [];
$data.push({ username : document.getElementById('username').value });
$data.push({ password : document.getElementById('password').value });
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", this.getAttribute('action'), true);
xhttp.send($data);
});