Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:写之前先规划一下, 不要上来就写, 把步骤想清楚, 就不难了
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ajax---GET请求</title>
</head>
<body>
<script>
//1,创建ajax对象
var ajaxGet = new XMLHttpRequest();
//2,监听请求
// 每当 readyState 改变时,就会触发 onreadystatechange 事件。(存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。)
// status : 200: "OK" 。 404: 未找到页面
ajaxGet.onreadystatechange = function(){
if(ajaxGet.readyState === 4 && ajaxGet.status === 200){
// responseText 获得字符串形式的响应数据。
console.log(ajaxGet.responseText);
}
};
//3,初始化参数
//ajax.open(请求类型,请求URL,是否异步)
ajaxGet.open("GET",'test.php',true);
//4,发送请求
ajaxGet.send(null);
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ajax---POST</title>
</head>
<body>
<script>
//1,创建ajax对象
var ajaxPost = new XMLHttpRequest();
// 2,监听
ajaxPost.onreadystatechange=function(){
if(ajaxPost.readyState === 4 && ajaxPost.status === 200){
console.log(ajaxPost.responseText);
}
};
// 3,提交参数初始化
ajaxPost.open("POST","test.php",true);
// 4,设置请求头,模拟表单数组类型发送
// application/x-www-form-urlencoded是默认值
ajaxPost.setRequestHeader('content-type','application/x-www-form-urlencoded');
//准备要发送的数据
var user = {
account:"admin",
password:123456,
};
//转换user为JSON字符串
var userdata = JSON.stringify(user);
ajaxPost.send(userdata);
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ajax---POST请求2</title>
</head>
<body>
<script>
// 1,创建对象
var ajaxPost = new XMLHttpRequest();
// 2,监听
ajaxPost.onreadystatechange=function(){
if(ajaxPost.readyState ===4 && ajaxPost.status === 200){
console.log(ajaxPost.responseText);
}
};
// 3,提交参数初始化
ajaxPost.open("POST","test1.php",true);
// 4,json字符串数据提交
ajaxPost.setRequestHeader('content-type','application/json;charset=utf-8');
var user = {
account:"admin",
name:"管理员",
};
// 5,提交
var datauser = JSON.stringify(user);
ajaxPost.send(datauser);
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajax_POST__formData</title>
</head>
<body>
<script>
// 1,创建对象
var ajaxform=new XMLHttpRequest();
ajaxform.onreadystatechange = function(){
if(ajaxform.readyState === 4 && ajaxform.status === 200)
{
console.log(ajaxform.response);
}
};
ajaxform.open("POST","test2.php",true);
// FormData 接口提供了一种表示表单数据的键值对的构造方式
var data = new FormData();
data.append("account","admin");
data.append("password","123456");
ajaxform.send(data);
</script>
</body>
</html>
<?php
if($_GET){
$user['account'] = "admin";
$user['user'] = "管理员";
$user['tel'] = 10010;
//将数据转换为JSON
echo json_encode($user);
}
if($_POST){
// print_r($_POST);
//转换为字符串
$data = key($_POST);
//将data转换为PHP可以处理的数据(json转为PHP对象、数组)
$user = json_decode($data);
print_r($user);
$user = json_decode($data,true);
print_r($user);
echo $user['account'];
echo '<hr>';
}
<?php
$data = file_get_contents('php://input');
//echo $data;
$user = json_decode($data,true);
echo $user['name'];