• AJAX概念及入门案例


    目录

    一、AJAX概念

    二、AJAX入门案例


    一、AJAX概念

    概念:AJAX(Asynchronous JavaScript And XML):异步的JavaScript和XML

    AJAX作用:

    1、与服务器进行数据交换:通过AJAX可以给服务器发送请求,并获取服务器响应的数据

    使用了AJAX和服务器进行通信,就可以使用HTML+AJAX来替换JSP页面

    2、异步交换,可以在不重新加载整个页面的情况下,与服务器交换数据并更新部分网页的技术,如:搜索联想、用户名是否可用校验,等等。。。

     同步异步区别对比:

     二、AJAX入门案例

     1、编写AjaxServlet,并使用response输出字符串

    2、创建XMLHttpRequest对象:用于和服务器交换数据

    1. var xhttp;
    2. if (window.XMLHttpRequest) {
    3. xhttp = new XMLHttpRequest();
    4. } else {
    5. // code for IE6, IE5
    6. xhttp = new ActiveXObject("Microsoft.XMLHTTP");
    7. }

    3、向服务器发送请求,默认异步,false为同步

    1. //发送请求
    2. xhttp.open("GET", "url");
    3. xhttp.send();

    4、获取服务器响应数据

    1. xhttp.onreadystatechange = function() {
    2. if (this.readyState == 4 && this.status == 200) {
    3. alert(this.responseText);
    4. }
    5. };

    代码示例:

    AjaxServlet代码:

    1. import javax.servlet.*;
    2. import javax.servlet.http.*;
    3. import javax.servlet.annotation.*;
    4. import java.io.IOException;
    5. @WebServlet("/ajaxServlet")
    6. public class AjaxServlet extends HttpServlet {
    7. @Override
    8. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    9. //1.响应数据
    10. response.getWriter().write("hello ajax");
    11. }
    12. @Override
    13. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    14. this.doGet(request, response);
    15. }
    16. }

    ajax-demo.html代码:

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>Title</title>
    6. </head>
    7. <body>
    8. <script>
    9. //1.创建核心对象
    10. var xhttp;
    11. if (window.XMLHttpRequest) {
    12. xhttp = new XMLHttpRequest();
    13. } else {
    14. // code for IE6, IE5
    15. xhttp = new ActiveXObject("Microsoft.XMLHTTP");
    16. }
    17. //2.发送请求
    18. xhttp.open("GET", "http://localhost:8080/ajax-demo/ajaxServlet");
    19. xhttp.send();
    20. //3.获取响应
    21. xhttp.onreadystatechange = function() {
    22. if (this.readyState == 4 && this.status == 200) {
    23. alert(this.responseText);
    24. }
    25. };
    26. </script>
    27. </body>
    28. </html>

    访问ajaxServlet时:

    访问ajax-demo.html时:

     浏览器开发者工具显示异步:

  • 相关阅读:
    rust 快速一览
    微信小程序案例:2-2本地生活
    gateway的基本使用
    mac如何卸载应用并删除文件,2023年最新妙招大公开!
    暴雨信息|低碳发展共拓数字能源产业绿色空间
    网络安全(黑客)自学笔记
    华纳云:远程桌面服务器出现乱码是什么原因?
    AOP是什么?如何使用AOP?
    【C++】多态 ⑫ ( 多继承 “ 弊端 “ | 多继承被禁用的场景 | 菱形继承结构的二义性 | 使用虚继承解决菱形继承结构的二义性 )
    C语言字符函数和字符串函数(1)
  • 原文地址:https://blog.csdn.net/m0_61961937/article/details/125009859