Blogger Information
Blog 28
fans 0
comment 0
visits 15806
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
2018-09-13JSON+AJAX
阿小的博客
Original
1121 people have browsed it

实例

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ajax实战:表单验证</title>
</head>
<body>
<form>
<p>邮箱:<input type="email" name="email"><p>
<p>密码:<input type="password" name="password"></p>
<p><button type="button" name="btn">提交</button></p>

</form>

<script type="text/javascript">
	let btn = document.getElementsByTagName('button')[0];
	
	btn.onclick = function() {
		//1.创建XMLHTTPRequest()
		let xhr = new XMLHttpRequest();
		
		//2.监听响应状态       onreadystatechange()事件,监听服务器状态变化
		xhr.onreadystatechange = function() {
			if(xhr.readyState === 4) {	//readyState属性:请求状态的值,就绪状态4
				if(xhr.status === 200) {	//status属性:请求的状态码,200说明已从服务器上返回数据
					let p = document.createElement('p');
					p.style.color = 'red';
					let data = JSON.parse(xhr.responseText);	//将PHP传回来的json字符串转换成js对象
					if(data.status == 1){
						p.innerHTML = data.msg;
					}else{
						p.innerHTML = data.msg;
					}
					//p.innerHTML = xhr.responseText;
					document.forms[0].appendChild(p);
					
					setTimeout(function() {
						document.forms[0].removeChild(p);
						btn.disabled = false;
						
						if(data.status == 1){
							location.href="admin.php";
						}
					},2000);
					btn.setAttribute('disabled',false);
				}else{
					alert('响应失败'+xhr.status);
				}
			}else{
				//'HTTP正在发送请求'	可放一张加载图片
				//alert(xhr.readyState);
			}
		};
		
		//3.请求参数设置
		xhr.open('post','inc/check.php',true);
		
		//4.post方式传输时要设置头信息
		xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		
		//5.发送请求
		let data = {
			email:document.getElementsByName('email')[0].value,
			password:document.getElementsByName('password')[0].value,
		};
		
		let json_data = JSON.stringify(data);	//将js对象转换为json格式的字符串
		
		xhr.send('data=' + json_data);
		
		//禁用按钮
		btn.setAttribute('disabled',false);
	}
</script>
</body>
</html>

运行实例 »

点击 "运行实例" 按钮查看在线实例


Correction status:qualified

Teacher's comments:代码记得加上高亮啊!
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post