博客列表 >Ajax原生实现方式

Ajax原生实现方式

JUNL的博客1111
JUNL的博客1111原创
2018年04月11日 16:41:57609浏览

实例

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Ajax入门</title>
</head>
<body>
	<!--<h2>Ajax</h2>-->
	<form action ="api/check.php" method="post">
	<fieldset>
		<legend>用户登录</legend>
		<p>
			<lable for="email">邮箱:</lable>
			<input type="text" name=""email" id="email">
		</p>
		<p>
			<lable for="password">密码:</lable>
			<input type="password" name="password" id="password">
		</p>
		<p><button>登录</button>
		<span id="tips" style="font-size:1.2em;font-weight:bolder;color:red;"></span>
	</p>
	</fieldset>
	</form>
</body>
</html>
<!--<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>-->
<script type="text/javascript">
	var btn=document.getElementsByTagName('button')[0]
	btn.onclick=function(){
		//alert('登录成功')
		//获取用户提交的数据
		var email=document.getElementById('email').value
		var password=document.getElementById('password').value
		//将用户数据拼装成查询字符串
		var data='email='+email+'&password='+password  
		//1创建 XHR对象
		var xhr =new XMLHttpRequest()
		//2.事件监听
		xhr.onreadystatechange=function(){
			
			if (xhr.readyState == 4 && xhr.status == 200){
			var tips =document.getElementById('tips')
		if(xhr.responseText =='1'){
			tips.innerHTML='登录成功,正在跳转。。'

			setTimeout(function(){
				location.href='api/index.php'},2000)
		

			}else{
				tips.innerHTML='邮箱或密码错误码。。。'
			document.getElementById('email').focus()
			//setTimeout(function(){location.href='api/index.php'},2000)}
			setTimeout("tips.innerHtml=''",2000)
		}
	}
		


		}
		//3 建立连接
		xhr.open('POST','api/user.php?m=login',true)
		//4 发送请求
		xhr.setRequestHeader('content-type','application/x-www-form-urlencoded')
		xhr.send(data)
		//5 设置回调函数
		//DOM操作



 return false
}
</script>

运行实例 »

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

实例

<?php 
echo '<h1 style="color:red">登录成功</h1>';

运行实例 »

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

实例

<?php 
if ($_GET['m'] == 'login') {
	if ($_POST['email'] == 'admin@php.cn' && $_POST['password'] == '123456'){
			echo '1';
		}
	else {
		echo '0';
	}
}

运行实例 »

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


声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议