AJAX
一、概念
全称ASynchronous JavaScript And XML
异步的javascript和xml,是指一种创建交互式、快速动态网页应用的网页开发技术,无需重新加载整个网页的情况下,能够更新部分网页的技术。
通过在后台与服务器进行少量数据交换,Ajax 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
异步和同步
异步和同步建立在客户端和服务器端相互通信的基础上,换言之XMLHttpRequest 是 AJAX 的基础
- 同步:客户端必须等待服务器端的响应。在等待的期间客户端不能做其他操作
- 异步:客户端不需要等待服务器端的响应。在服务器处理请求的过程中,客户端可以进行其他的操作
画图说明
二、实现方式
1、原生的JS实现方式(了解)
① xhr对象创建过程及其写法
③ xhr获取服务器响应的属性介绍及其写法
④ 处理服务器返回的响应前需要判断是否成功接收服务器返回的响应
举例示范
<!DOCTYPE html>
<html lang="en">
<head>
<Meta charset="UTF-8">
<title>Title</title>
<script>
function fun() {
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","ajaxServlet?username=tom",true);
xmlhttp.send();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
}
</script>
</head>
<body>
<input type="button" value="发送异步请求" onclick="fun()">
<input type="text">
</body>
</html>
服务器端代码
@WebServlet("/ajaxServlet")
public class AjaxServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws servletexception, IOException {
String username = request.getParameter("username");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printstacktrace();
}
System.out.println(username);
response.getWriter().write("hello:"+username);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws servletexception, IOException {
this.doPost(request, response);
}
}
效果截图
解释:代码中html页面中的第二个input是为了掩饰异步和同步的区别,当我们设置为同步时,该input中无法输入内容但是当我们设置为异步的时候,该输入框内可以出入内容
2、JQuery的实现方式
(1)$.ajax()
(2)$.get()
(3)$.post()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。