abstract:<!DOCTYPE html><html><head> <meta charset="utf-8"> <title>使用AJAX与JSON进行无刷新的表单验</title></head><body><h3>用户登录</h3><form> <p
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>使用AJAX与JSON进行无刷新的表单验</title>
</head>
<body>
<h3>用户登录</h3>
<form>
<p>用户名:<input type="user" name="user"></p>
<p>密 码:<input type="password" name="password"></p>
<p><button>登入</button></p>
</form>
<script>
let btn = document.getElementsByTagName('button')[0];
btn.onclick = function () {
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (xhr.readyState === 4) {
if (xhr.status === 200) {
let p = document.createElement('p');
p.style.color = 'red';
let json = JSON.parse(xhr.responseText);
if (json.status === 1) {
p.innerHTML = json.msg;
} else if (json.status == 0) {
p.innerHTML = json.msg;
}
document.forms[0].appendChild(p);
btn.disabled = true;
setTimeout(function(){
document.forms[0].removeChild(p);
btn.disabled = false;
if (json.status == 1) {
location.href = 'admin.php';
}
},2000);
} else {
alert('失败'+xhr.status);
}
} else {
}
}
xhr.open('post','inc/check.php',true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
let data = {
user: document.getElementsByName('user')[0].value,
password: document.getElementsByName('password')[0].value
};
let data_json=JSON.stringify(data);
xhr.send('data='+data_json);
}
</script>
</body>
</html>