在做登錄的時候,需要ajax提交驗證,但是發現點擊button會自動submit表單,代碼如下
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登錄</title>
<style type="text/css">
html {
width: 100%;
height: 100%;
}
body {
width: 100%;
height: 100%;
margin: 0;
background-color: #3C8DBC;
}
form {
width: 400px;
height: 400px;
top: 50%;
left: 50%;
margin-left: -200px;
margin-top: -200px;
position: absolute;
background-color: #FFF;
background-color: rgba(255, 255, 255, 0.3);
display: flex;
border-radius: 10px;
flex-direction: column;
justify-content: center;
align-items: center;
box-shadow: 15px 0 15px -15px #000, -15px 0 15px -15px #000; -
-borderWidth: 2px;
border-radius: var(- -borderWidth);
}
h1 {
color: #FFF;
font-weight: bold;
text-shadow: 2px 2px 5px #002478;
}
.loginInput {
width: 173px;
height: 24px;
}
.loginBtn {
height: 30px;
color: white;
font-size: 16px;
background-color: #3C8DBC;
border-color: #3C8DBC;
border-radius: 4px;
}
.loginBtn:hover {
background-color: #1360a7;
border-color: #1360a7;
}
</style>
</head>
<body>
<form action="login.do">
<h1>系統登陸</h1>
<hr>
<input type="text" class="loginInput" placeholder="登錄帳號"><br> <input
type="password" class="loginInput" placeholder="登錄密碼"><br>
<button class="loginInput loginBtn">按鈕點擊</button>
</form>
</body>
</html>
點擊提交後,會提交到form指定的action
原來是button在form裏面會submit事件,最後只能改成input,然後將類型設置爲submit,然後寫js方法返回false即可不自動提交表單
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登錄</title>
<style type="text/css">
html {
width: 100%;
height: 100%;
}
body {
width: 100%;
height: 100%;
margin: 0;
background-color: #3C8DBC;
}
form {
width: 400px;
height: 400px;
top: 50%;
left: 50%;
margin-left: -200px;
margin-top: -200px;
position: absolute;
background-color: #FFF;
background-color: rgba(255, 255, 255, 0.3);
display: flex;
border-radius: 10px;
flex-direction: column;
justify-content: center;
align-items: center;
box-shadow: 15px 0 15px -15px #000, -15px 0 15px -15px #000; -
-borderWidth: 2px;
border-radius: var(- -borderWidth);
}
h1 {
color: #FFF;
font-weight: bold;
text-shadow: 2px 2px 5px #002478;
}
.loginInput {
width: 173px;
height: 24px;
}
.loginBtn {
height: 30px;
color: white;
font-size: 16px;
background-color: #3C8DBC;
border-color: #3C8DBC;
border-radius: 4px;
}
.loginBtn:hover {
background-color: #1360a7;
border-color: #1360a7;
}
</style>
</head>
<body>
<form action="login.do" οnsubmit="return login();">
<h1>系統登陸</h1>
<hr>
<input type="text" class="loginInput" placeholder="登錄帳號"><br>
<input type="password" class="loginInput" placeholder="登錄密碼"><br>
<input type="submit" class="loginInput loginBtn" value="登錄"><br>
</form>
<script type="text/javascript">
function login() {
// 此處寫 ajax 請求後臺代碼
alert('登錄成功');
return false;
}
</script>
</body>
</html>