一、AJAX简介
ajax (Asynchronous Javascript And XML)其实就是异步的javaScript和XML。本质就是在HTTP协议的基础上以异步的方式与服务器进行通信。
二、AJAX处理网络请求步骤
1.通过XMLHttpRequest类创建xhr对象
2.为xhr对象添加属性与回调方法
3.令xhr对象执行open()方法,指明请求被发往某处
4.令xhr对象执行send()方法,发出请求。
三、post请求及get请求
1、get请求
比如:点击button按钮发送一个请求
<button onclick="sendMsg()">发送请求</button>
<script>
function sendMsg(){
//创建一个XMLHttpRequest()对象
var xhr = new XMLHttpRequest();
//监听状态改变
xhr.onreadystatechange = function(){
//判断状态值 0-4五种状态 4代表完成状态
if(xhr.readyState === 4){
//判断状态码 200 为正常
if(xhr.status === 200){
var resp =JSON.parse(xhr.responseText)
console.log(resp);
document.querySelector('div').innerHTML =`
<h2>编号:${resp.id}</h2>
<h2>标题:${resp.title}</h2>
`
}
}
}
// 打开连接
xhr.open("get" , "./data.php?id=1")
// 发送请求
xhr.send()
}
</script>
<?php
$id = $_GET["id"];
echo json_encode(array(
"id" => $id,
"title"=>"hello ajax"
));
?>
结果如下图所示:
当点击按钮之后,会成功在div中添加两个h2及文本内容
2、post请求
比如:点击button按钮发送一个请求
<button onclick="sendMsg()">发送请求</button>
<script>
function sendMsg(){
//创建一个XMLHttpRequest()对象
var xhr = new XMLHttpRequest();
//监听状态改变
xhr.onreadystatechange = function(){
//判断状态值 0-4五种状态 4代表完成状态
if(xhr.readyState === 4){
//判断状态码 200 为正常
if(xhr.status === 200){
var resp = JSON.parse(xhr.responseText)
console.log(resp);
document.querySelector("div").innerHTML=`
<h2>姓名:${resp.name}</h2>
<h2>年龄:${resp.age}</h2>
<h2>余额:${resp.money}</h2>
`
}
}
}
// 设置请求头的content-type
xhr.setRequestHeader("content-type" , "application/x-www-form-urlencoded")
// 打开连接
xhr.open("post" , "./data.php?id=1")
// 发送请求
xhr.send("name=zhnagsan&age=18")
}
</script>
<?php
// echo "hello post"
$name=$_POST("name");
$age=$_POST("age");
echo json_encode(array(
"name" => $name,
"age" => $age,
"money" => 99999
));
?>