Blogger Information
Blog 22
fans 3
comment 3
visits 16394
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
前后端json数据交互-2019年7月21日1点45分
辰晨的博客
Original
641 people have browsed it

json数据交互

1.前端json数据发送

将数据用对象封装起来,用JSON.stringify(obj)将数据转换为json格式的数据发送给后端,并将请求头改为json格式request.setRequestHeader('contant-type','application/json;charset=utf-8');

2.后端json数据解析

将服务器返回的json字符串解析为JS对象,var obj = JSON.parse(request.responseText);根据status状态值将数据做进一步的处理

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>post表单验证</title>
</head>
<body>
<h2>用户登录</h2>
<form action="" name="login">
    <p>
        <label for="username">用户:</label>
        <input type="text" name="username" id="username" placeholder="UserName">
    </p>
    <p>
        <label for="email">邮箱:</label>
        <input type="text" name="email" id="email" placeholder="example@email.com">
    </p>
    <p>
        <label for="password">密码:</label>
        <input type="password" name="password" id="password" placeholder="******" >
    </p>
    <p>
        <button type="button" name="submit">提交</button>
    </p>
</form>

<script>
	var login = document.forms.namedItem('login');
	var btn = login.submit; 
	var request = new XMLHttpRequest();

	login.username.addEventListener('blur',isEmpty,false);
	login.email.addEventListener('blur',isEmpty,false);
	login.password.addEventListener('blur',isEmpty,false);
	function isEmpty(ev){
		if(ev.target.value.length === 0){
			if(ev.target.nextElementSibling === null){
				var tips = document.createElement('span');
				tips.style.color = 'red';
				switch(ev.target.name){
					case 'username':
					tips.innerText = '用户名不能为空';
					break;
					case 'email':
					tips.innerText = '邮箱不能为空';
					break;
					case 'password':
					tips.innerText = '密码不能为空';
					break;
					default:
					'未定义错误';
				}
				ev.target.parentNode.appendChild(tips);
			}
			ev.target.focus();
		}
	}

	login.username.addEventListener('input',clearTips,false);
	login.email.addEventListener('input',clearTips,false);
	login.password.addEventListener('input',clearTips,false);
	function clearTips(ev){
		var tips = ev.target.nextElementSibling;
		if(tips !== null){
			tips.parentNode.removeChild(tips);
		}
	}
	btn.addEventListener('click', check, false);
	function check(ev){
		var username = login.username.value;
		var email = login.email.value;
		var password = login.password.value;

		if(username.length === 0 || email.length === 0 || password.length ===0){
			ev.target.removeEventListener('click',check,false);
			var blurEvent = new Event('blur');
			login.username.dispatchEvent(
				blurEvent);
			return false;
		}

		var obj = {
			username:username,
			email:email,
			password:password
		};
		var data = JSON.stringify(obj);

		request.addEventListener('readystatechange',successCallback,false);
		request.open('POST','check.php',true);
		request.setRequestHeader('contant-type','application/json;charset=utf-8');
		
		request.send(data);
	}
	function successCallback(ev){
		if(request.readyState===4){
			var obj = JSON.parse(request.responseText);
			var tips = document.createElement('span');
			var url = '';
			switch(obj.status){
				case 1 :
				tips.style.color = 'green';
				tips.innerText = obj.message + ',正在跳转中...';
				url = 'admin.php';
				break;
			case 0 :
				tips.style.color = 'red';
				tips.innerText = obj.message ;
				url = 'index.html';
				break;
			default:
				alert('未知错误');
				break;
			}
			btn.parentNode.appendChild(tips);
			setTimeout(function(){
				location.href = url;
			},2000);
		}
	}
</script>

</body>
</html>

运行实例 »

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

<?php
session_start();

// 获取表单提交的数据
$username = $_POST['username'];
$email = $_POST['email'];
$password = sha1($_POST['password']);


// 为简化代码,不用数据表验证,使用硬编码,只验证邮箱与密码
if ($username === 'admin' && $email === 'admin@php.cn' && $password === sha1('123456')) {
    $_SESSION['username'] = $username;
    $_SESSION['email'] = $email;
    echo json_encode(['status'=>1, 'message'=>'验证成功']);
} else {
    echo json_encode(['status'=>0, 'message'=>'验证失败']);
}
exit;

运行实例 »

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


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