Ajax和json
json
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<ul>
<li></li>
<li></li>
<li></li>
</ul>
<script>
// 将json字符串转为js对象
// 多行字符串需要加入'\'
var js1 = '{\
"name":"admin",\
"age":20,\
"like":"打篮球"\
}';
var obj = JSON.parse(js1);
console.log(obj);
var lis = document.querySelector('li:first-of-type');
lis.innerHTML = obj.name;
var lis1 = document.querySelector('li:nth-of-type(2)');
lis1.innerHTML = obj.age;
var lis2 = document.querySelector('li:last-of-type');
lis2.innerHTML = obj.like;
var str = '{\
"name": "admin",\
"age": 20,\
"marriage": true,\
"course": {\
"name": "php",\
"grade": 90\
}\
}';
// parse可以转入参数对转换数据进行处理
var obj = JSON.parse(str, function (key, value) {
if (key === "marriage") {
return '不要再来骚扰我了';
}
return value;
});
console.log(obj);
var pe = {
name: obj.name,
age: obj.age,
courseName: obj.course.name,
courseGrade: obj.course.grade,
};
console.log(pe);
// 渲染到页面
var ul = document.createElement("ul");
var li = "";
for (var key in pe) {
li += "<li>" + pe[key] + "</li>";
}
console.log(li);
ul.innerHTML = li;
// 插入到页面中
document.body.appendChild(ul);
</script>
</body>
</html>
Ajax
GET方式
var btn = document.querySelector('button');
btn.addEventListener('click', get, false);
function get() {
// GET请求
// 1.创建ajax对象
var aj = new XMLHttpRequest();
// 2.监听请求
aj.onreadystatechange = function () {
if (aj.readyState === 4 && aj.status === 200) {
console.log(aj.responseText);
// 凡是涉及页面DOM操作都放在监听请求中
var obj = JSON.parse(aj.responseText);
console.log(obj);
document.querySelector('p:first-of-type').innerHTML = obj.name;
document.querySelector("p:nth-of-type(2)").innerHTML = obj.age;
document.querySelector("p:last-of-type").innerHTML = obj.course;
}
};
// 3.初始化请求参数
// open(请求类型,请求的URL地址,是否异步/默认异步)
aj.open("GET", "0812.php?id=2");
// 4.发送请求(get方式没有请求参数)
aj.send(null);
}
php代码
<?php
$users = [
['id' => 1, 'name' => 'admin', 'age' => 18, 'course' => 'PHP'],
['id' => 2, 'name' => 'useradmin', 'age' => 20, 'course' => 'JAVA'],
];
$id = $_GET['id'];
foreach ($users as $value) {
if ($value['id'] == $id) {
echo json_encode($value);
}
}
POST方式
方式1
var btn = document.querySelector('button');
btn.addEventListener('click', get, false);
function get() {
// POST请求
// 1.创建ajax对象
var aj = new XMLHttpRequest();
// 2.监听请求
aj.onreadystatechange = function () {
if (aj.readyState === 4 && aj.status === 200) {
console.log(aj.responseText);
}
};
// 3.初始化请求参数
// open(请求类型,请求的URL地址,是否异步/默认异步)
aj.open("POST", "0812.php");
// 4.设置请求头(用键值对模拟表单方式发送数据)
aj.setRequestHeader("content-type", "application/x-www-form-urlencoded");
// 准备数据(可以写入对象通过方法转换为json字符串后再发送)
var user = {
name: "admin",
password: "123456",
};
var date = JSON.stringify(user);
// 5.发送请求(可以手工加入键)
aj.send("user=" + date);
}
PHP代码
print_r($_POST);
$user = json_decode($_POST['user']);
echo $user->name . ":" . sha1($user->password);
POST方式2
// POST方式2(直接发送json字符串)
var btn = document.querySelector('button');
btn.addEventListener('click', get, false);
function get() {
// POST请求
// 1.创建ajax对象
var aj = new XMLHttpRequest();
// 2.监听请求
aj.onreadystatechange = function () {
if (aj.readyState === 4 && aj.status === 200) {
console.log(aj.responseText);
}
};
// 3.初始化请求参数
// open(请求类型,请求的URL地址,是否异步/默认异步)
aj.open("POST", "0812.php");
// 4.设置请求头
// 直接把请求头内容设置为json
aj.setRequestHeader("content-type", "application/json;charset=utf-8");
// 准备数据(可以写入对象通过方法转换为json字符串后再发送)
var user = {
name: "admin",
password: "123456",
};
var date = JSON.stringify(user);
// 5.发送请求
aj.send(date);
}
php代码
// POST方式2
// 前端不是通过模拟表单进行发送那么用$_POST里面就没有数据需要在输入流中获取数据
$data = file_get_contents("php://input");
// 然后解析json
$user = json_decode($data);
echo $user->name . ':' . $user->password;
POST方式3(使用表单对象/推荐)
var btn = document.querySelector('button');
btn.addEventListener('click', get, false);
function get() {
// POST请求
// 1.创建ajax对象
var aj = new XMLHttpRequest();
// 2.监听请求
aj.onreadystatechange = function () {
if (aj.readyState === 4 && aj.status === 200) {
console.log(aj.responseText);
}
};
// 3.初始化请求参数
// open(请求类型,请求的URL地址,是否异步/默认异步)
aj.open("POST", "0812.php");
// 4.使用FormData对象发送数据
var date = new FormData();
// 向对象中添加数据
date.append("name", "admin");
date.append("password", "789456");
// 5.发送请求
aj.send(date);
}
php代码
// POST方式3
print_r($_POST);
Ajax-FormData-JSON
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ajax案例演示</title>
</head>
<body>
<form method="POST" onsubmit="return false">
<input type="email" name="email" placeholder='exam@email.com' required autofocus>
<input type="password" name="password" placeholder='请输入密码' required>
<button>登录</button>
</form>
<script>
// 获取元素
var form = document.querySelector('form');
var btn = document.querySelector('form>button');
// 2.给按钮绑定事件
btn.onclick = function () {
// 1.创建ajax对象
var aj = new XMLHttpRequest();
// 2.监听请求
aj.onreadystatechange = function () {
if (aj.readyState === 4 && aj.status === 200) {
// console.log(aj.responseText);
var obj = JSON.parse(aj.responseText);
console.log(obj);
var p = document.createElement('p');
switch (obj.status) {
case 1:
error = obj.message;
p.style.color = "green";
break;
case 2:
error = obj.message;
p.style.color = "red";
break;
default:
error = '未知错误';
}
p.innerHTML = error;
form.appendChild(p);
}
}
// 3.初始化请求参数
aj.open("POST", "0812.php");
// 4.使用FormData对象组织数据,最终以表单数据方式发送
var data = new FormData(form);
// data.append("email", form.email.value);
// data.append("password", form.password.value);
// 5.发送请求
aj.send(data);
};
</script>
</body>
</html>
php代码
$user = ["email" => "mingzi@qq.com", "password" => "123456"];
$email = $_POST['email'];
$password = $_POST['password'];
if ($email == $user['email'] && $password == $user['password']) {
echo json_encode(["status" => 1, "message" => "验证通过"]);
} else {
echo json_encode(["status" => 2, "message" => "邮箱或者密码错误"]);
}
总结
1.了解了异步请求的执行流程
2.有个疑问 后端返回的数据一定要通过JSON字符串返回前端,前端才能调用是吗