AJAX
一,概念
ASynchronous JavaScript And XML:异步的JavaScript和XML
客户端与服务器端在通信上的同步和异步:
同步:客户端必须等待服务器的响应,在等待过程中客户端不能做其他操作。
异步:客户端在等待服务器响应的过程中可以进行其他的操作。
AJAX是一种无需重新加载整个页面,就能够更新部分网页的技术。
核心思想:异步加载、局部刷新
作用:提升用户体验
二,实现方式
2.1 原生的js
<html>
<head>
<title>Title</title>
<script>
function func(){
var user = document.getElementById("user").value;
//1.创建核心对象
var xmlhttp;
if(window.XMLHttpRequest){
// 高版本的浏览器:IE7+、chrome、firefox
xmlhttp = new XMLHttpRequest();
}
else{
// 低版本的浏览器
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//2.建立连接
/*
参数1:请求方式
GET:请求参数需要拼接在url之后,send()方法参数为空
POST:请求参数写在send()方法中
参数2:请求的地址
参数3:同步还是异步,异步(true),同步(false)
*/
xmlhttp.open("GET","ajaxServlet?user="+user,true);
//3.发送请求
xmlhttp.send();
/*xmlhttp.open("POST","ajaxServlet",true);
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlhttp.send("user=zhangfei");*/
//4.接收并处理服务器的响应结果
xmlhttp.onreadystatechange = function(){
//判断readystate的状态是否为已就绪4,判断status响应是否为200
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
var msg = xmlhttp.responseText;
alert(msg);
}
}
}
</script>
</head>
<body>
<input type="text" id="user">
<input type="button" onclick="func()" value="发送异步请求">
</body>
</html>
2.2 jquery实现
<html>
<head>
<title>Title</title>
<script src="js/jquery-3.3.1.min.js"></script>
<script>
function func1(){
var user = document.getElementById("inp1").value;
var pwd = document.getElementById("inp2").value;
$.ajax({
// 请求方式
type:"GET",
// 请求的参数
data:"user="+user+"&pwd="+pwd,
// 请求的地址
url:"ajaxServlet",
// 服务器响应后触发,该函数用于处理接收到的结果,参数就是响应结果
success:function(d){
alert(d);
},
// 发送错误时触发
error:function(){
alert("出错了");
},
// 响应结果的类型:text文本,json对象,该值决定了success后方法的参数类型
dataType:"text"
});
}
function func2(){
var user = document.getElementById("inp1").value;
var pwd = document.getElementById("inp2").value;
/*
参数1:请求的地址
参数2:请求的参数
参数3:服务器响应后触发,用于接收处理响应内容
参数4:响应结果的类型
*/
$.get("ajaxServlet","user="+user+"&pwd="+pwd,function(data){
alert(data);
},"text")
}
function func3(){
var user = document.getElementById("inp1").value;
var pwd = document.getElementById("inp2").value;
/*
参数1:请求的地址
参数2:请求的参数
参数3:服务器响应后触发,用于接收处理响应内容
参数4:响应结果的类型
*/
$.post("ajaxServlet","user="+user+"&pwd="+pwd,function(data){
alert(data);
},"text")
}
</script>
</head>
<body>
<input type="text" name="user" id="inp1">
<input type="text" name="pwd" id="inp2">
<button onclick="func1()">ajax()发送异步请求</button>
<button onclick="func2()">get()发送异步请求</button>
<button onclick="func3()">post()发送异步请求</button>
</body>
</html>