原生Ajax: 表单验证
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>原生Ajax: 表单验证</title>
</head>
<body>
<form>
<p>邮箱:<input type="email" name="email" value="admin@155.com"></p>
<p>密码:<input type="password" name="password"></p>
</form>
<p><button onclick="check()" type="button">登录</button></p>
<P id="tips"></P>
</body>
</html>
<script>
function check(){
var forms = document.forms[0];
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
var obj = JSON.parse(xhr.responseText);
if(obj.code == 0){
document.getElementById('tips').style.color = 'blue';
document.getElementById('tips').innerHTML = obj.msg;
}
if(obj.code == 1){
document.getElementById('tips').style.color = 'red';
document.getElementById('tips').innerHTML = obj.msg;
}
}
}
xhr.open('post','check.php',true);
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
var data = 'email='+forms.email.value+'&password='+forms.password.value;
xhr.send(data);
}
</script>