原生js编写异步请求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="javascript:;">
<input type="text" class="mobile" name="username"> <br>
<input type="text" class="password" name="password"> <br>
<button class="login">登陆</button>
</form>
<script>
window.onload = function (){
var $ = name => document.querySelector(name);
$(".login").onclick = function (){
let _mobile = $(".mobile").value,
_password = $(".password").value;
sendData(_mobile,_password)
}
function sendData(mobile,password) {
let xmlhttp = new XMLHttpRequest();
xmlhttp.open("post","http://localhost:8080/login")
xmlhttp.setRequestHeader("Content-Type","application/json")
xmlhttp.send(JSON.stringify({
mobile,
password
}))
xmlhttp.onreadystatechange = function (){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
alert(xmlhttp.responseText);
}
}
}
}
</script>
</body>
</html>