目录
概念:AJAX(Asynchronous JavaScript And XML):异步的JavaScript和XML
AJAX作用:
1、与服务器进行数据交换:通过AJAX可以给服务器发送请求,并获取服务器响应的数据
使用了AJAX和服务器进行通信,就可以使用HTML+AJAX来替换JSP页面
2、异步交换,可以在不重新加载整个页面的情况下,与服务器交换数据并更新部分网页的技术,如:搜索联想、用户名是否可用校验,等等。。。
同步异步区别对比:
1、编写AjaxServlet,并使用response输出字符串
2、创建XMLHttpRequest对象:用于和服务器交换数据
- var xhttp;
- if (window.XMLHttpRequest) {
- xhttp = new XMLHttpRequest();
- } else {
- // code for IE6, IE5
- xhttp = new ActiveXObject("Microsoft.XMLHTTP");
- }
3、向服务器发送请求,默认异步,false为同步
- //发送请求
- xhttp.open("GET", "url");
- xhttp.send();
4、获取服务器响应数据
- xhttp.onreadystatechange = function() {
- if (this.readyState == 4 && this.status == 200) {
- alert(this.responseText);
- }
- };
代码示例:
AjaxServlet代码:
- import javax.servlet.*;
- import javax.servlet.http.*;
- import javax.servlet.annotation.*;
- import java.io.IOException;
-
- @WebServlet("/ajaxServlet")
- public class AjaxServlet extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
-
- //1.响应数据
- response.getWriter().write("hello ajax");
- }
-
- @Override
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- this.doGet(request, response);
- }
- }
ajax-demo.html代码:
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Title</title>
- </head>
- <body>
-
-
- <script>
- //1.创建核心对象
- var xhttp;
- if (window.XMLHttpRequest) {
- xhttp = new XMLHttpRequest();
- } else {
- // code for IE6, IE5
- xhttp = new ActiveXObject("Microsoft.XMLHTTP");
- }
- //2.发送请求
- xhttp.open("GET", "http://localhost:8080/ajax-demo/ajaxServlet");
- xhttp.send();
- //3.获取响应
- xhttp.onreadystatechange = function() {
- if (this.readyState == 4 && this.status == 200) {
- alert(this.responseText);
- }
- };
-
- </script>
- </body>
- </html>
访问ajaxServlet时:
访问ajax-demo.html时:
浏览器开发者工具显示异步: