一、概念
AJax的全称为ASynchronous JavaScript And XML(异步的JavaScript和XML),是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。
二、实现
1、原生的JS实现方式
<html lang="en">
<head>
<meta charset="UTF-8">
<title>原生js实现ajax</title>
<script>
function fun() {
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", "ajaxServlet?username=tom", true);
xhttp.send();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let responseText = xhttp.responseText;
window.alert(responseText)
}
};
}
</script>
</head>
<body>
<input type="button" value="发送ajax请求" onclick="fun();">
<input type="text" value="">
</body>
</html>
2、JQeury实现方式 --> $.ajax()
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JQuery实现ajax</title>
<script src="./js/jquery-3.3.1.min.js"></script>
<script>
function fun() {
$.ajax({
type:"POST",
url:"ajaxServlet1",
data:{"username":"tom"},
dataType:"JSON",
success:function (data) {
window.alert(data);
},
error:function () {
window.alert("请求响应失败")
}
})
}
</script>
</head>
<body>
<input type="button" value="发送ajax请求" onclick="fun();">
<input type="text" value="">
</body>
</html>
3、JQeury实现方式 --> $.get()
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JQuery实现ajax</title>
<script src="./js/jquery-3.3.1.min.js"></script>
<script>
function fun() {
$.get("ajaxServlet",{"username":"tom"},function (data) {
window.alert(data);
},"json");
}
</script>
</head>
<body>
<input type="button" value="发送ajax请求" onclick="fun();">
<input type="text" value="">
</body>
</html>
4、JQeury实现方式 --> $.post()
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JQuery实现ajax</title>
<script src="./js/jquery-3.3.1.min.js"></script>
<script>
function fun() {
$.post("ajaxServlet",{"username":"tom"},function (data) {
window.alert(data);
},"JSON");
}
</script>
</head>
<body>
<input type="button" value="发送ajax请求" onclick="fun();">
<input type="text" value="">
</body>
</html>