Blogger Information
Blog 33
fans 0
comment 0
visits 20847
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
js 的ajax 2018年9月13日
马聪 15558002279的博客
Original
674 people have browsed it

2登录验证:

实例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>
<h3>用户登录</h3>
<form>
    <p>用户名: <input type="text" name = "user"></p>
    <p>密码: <input type="password" name = "user"></p>
    <input type="button" value="登录" id = "submitBtn"> 
</form>
<script>
	document.getElementById('submitBtn').onclick = function(event){
	
		//实例化ajax对象
		var xhr = new XMLHttpRequest();
		xhr.onreadystatechange = function(){
			if (xhr.readyState===4) {
				if(xhr.status===200){
				new_boj = document.createElement('p')
				res = JSON.parse(xhr.responseText)
					if(res.status==1){
					new_boj.innerHTML = res.msg
					document.body.appendChild(new_boj);
					setTimeout(function(){
						window.location.href="admin.html";
					},1000)
					}else{
					new_boj.innerHTML = res.msg
					document.body.appendChild(new_boj);
					}
				}else{
					console.log('连接失败');
				}
			}else{
			}
		}
		xhr.open("post",'ajax.php');
		//4. 设置头信息,将内容类型设置为表单提交方式
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        var data = {
        	name: document.getElementsByName('user')[0].value,
        	pwd: document.getElementsByName('user')[1].value
        }
        var data= JSON.stringify(data)
        xhr.send("arr=" + data);
	event.preventDefault()
	}
</script>
</body>
</html>

运行实例 »

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

php脚本:

实例

<?php
 $obj = json_decode($_POST['arr']);
// echo $obj->name,$obj->pwd;

$pdo = new PDO("mysql:host=localhost;dbname=test","abc","abc");
$sql = "SELECT count(*) FROM `user` WHERE `name`=:name AND `pwd`=:pwd";
$stmt = $pdo->prepare($sql);
$data['name'] = $obj->name;
$data['pwd'] =$obj->pwd;
$stmt->execute($data);
$res = $stmt->fetchColumn();
if($res==1){
	$arr['status'] = 1;
	$arr['msg'] = "登录成功";
	echo json_encode($arr);
}else{
	$arr['status'] = 0;
	$arr['msg'] = "用户名或密码错误";
	echo json_encode($arr);
}
?>

运行实例 »

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

3.手写get方式ajax:

759890921462456289.jpg

Correction status:Uncorrected

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