Ajax异步调用

一、概述

Ajax全称是Asynchronous Javascript and XML,即异步的JavaScript和 XML。Ajax是一种Web应用技术,该技术是在JavaScript、DOM、服务器配合下,实现浏览器向服务器发送异步请求。

Ajax技术用于页面的局部更新,同步调用会对客户使用造成影响,比如当你想获取一张图片时,页面需要通过一系列请求,之后浏览器把整个页面重新发送,花费时间长。异步调用便解决了这个我问题。Ajax异步请求方式不向服务器发出请求,会得到数据后再更新页面(通过DOM操作修改页面内容),整个过程不会发生页面跳转或刷新操作。

二、jQuery框架

要实现Ajax异步刷新就需要使用到JavaScript和DOM技术,但使用JavaScript实现Ajax异步刷新比较复杂,而且需要考虑到跨域等问题,因此,人们在Web项目开发过程中提供了很多框架,对Ajax做了一系列封装简化,使操作更方便快捷。其中,最常用的框架为jQuery。

2.1 jQuery基础知识

官网下载后,添加再web目录下,之后在需要的HTMl和JSp中引入即可。

引入方式:

<script src="jquery-3.7.1.js"></script>

jQuery的常用操作包括选择器的使用、元素对象的操作、事件的绑定、链式编程.

jQuery中的load()方法

load(url,data,callback)

  • url:必选,指定加载资源的路径
  • data:可选,发送至服务器的数据
  • callback:可选,请求完成时执行的函数

使用第一个参数

html 复制代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="/jquery-3.7.1.js"></script>
</head>
<body>
<button id="btn">加载数据</button>
<div id="box"></div>
<script type="text/javascript">
    $('#btn').click(function (){
        $('#box').load('http://localhost:8080/jQuery/data.jsp')
    });
</script>
</body>
</html>

data.jsp

html 复制代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h3>静夜思</h3>
<h6>唐 李白</h6>
<pre>
  床前明月光,
  疑似地上霜。
  举头望明月,
  低头思故乡。
</pre>
</body>
</html>

运行结果

第二个参数

demo02.jsp

html 复制代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <title>Title</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#btn').click(function () {
                $('#box').load('http://localhost:8080/loadServlet', {username: 'zhangsan', password: '123'});
            });
        });
    </script>
</head>
<body>
<button id="btn">加载数据</button>
<div id="box"></div>
</body>
</html>

对应转发的servlet类

java 复制代码
@WebServlet("/loadServlet")
public class LoadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        resp.setContentType("text/html;charset=UTF-8");
        resp.getWriter().println("注册成功!<br> 用户名: " + username + ", 密码:" + password);
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPut(req, resp);
    }
}

第三个参数

回调函数,该函数在请求数据加载完成后执行。回调函数用于获取本次请求的相关信息,它有3个默认参数,分别表示响应数据、请求状态和XMLHttpRequest对象。 其中,请求状态共有5种,分别为success(成功)、notmodified(未修改)、error(错误)、timeout(超时)和parsererror(解析错误)。

在demo02.jsp中进行修改

html 复制代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <title>Title</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#btn').click(function () {
                $('#box').load('http://localhost:8080/loadServlet', {username: 'itcast', password: 123},
                    function(responseData, status, xhr){
                        console.log(responseData);	// 输出请求的数据
                        console.log(status);		// 输出请求状态
                        console.log(xhr);		// 输出XMLHttpRequest对象
                    })
            });
        });
    </script>
</head>
<body>
<button id="btn">加载数据</button>
<div id="box"></div>
</body>
</html>

发送GET和POST请求

浏览器向服务器发送的请求包括GET请求和POST请求,为此,jQuery提供了.get()方法和.post()方法,分别用于发送GET请求和POST请求。

$.get()方法请求

和load()类似,但多了一个dataType,其预期的服务器响应的数据类型( xml、html、text、script、json、jsonp)

html 复制代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="/jquery-3.7.1.js"></script>
</head>
<body>
<button id="btn">加载数据</button>
<div id="box"></div>
<script>
    $('#btn').click(function() {
        $.get('http://localhost:8080/jQuery/data.jsp', function(data) {
            $('#box').html(data);
        }, 'html');
    });
</script>
</body>
</html>

调用$.get()方法发送数据

$.post()方法发送数据

在jQuery中,发送GET请求调用.get()方法,发送POST请求调用.post()方法,两个方法使用方式完全相同,替换两者的方法名就可以在GET请求和POST请求方式之间切换。

html 复制代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="/jquery-3.7.1.js"></script>
</head>
<body>
<button id="btn">加载数据</button>
<div id="box"></div>
<script>
    $('#btn').click(function() {
        var userData = {username: 'itcast', password: 123};
        $.get('http://localhost:8080/loadServlet',userData,
            function(data) { $('#box').html(data); }, 'html');
    });
</script>
</body>

运行结果

相关推荐
毕设十刻7 分钟前
基于Vue的鲜花销售系统33n62(程序 + 源码 + 数据库 + 调试部署 + 开发环境配置),配套论文文档字数达万字以上,文末可获取,系统界面展示置于文末
前端·数据库·vue.js
IT_陈寒13 分钟前
Spring Boot 3.2震撼发布:5个必知的新特性让你开发效率提升50%
前端·人工智能·后端
San30.15 分钟前
JavaScript 深度解析:从 map 陷阱到字符串奥秘
开发语言·javascript·ecmascript
初遇你时动了情19 分钟前
前端使用TensorFlow.js reactjs调用本地模型 实现图像、文本、音频/声音、视频相关识别
前端·javascript·tensorflow
广州华水科技25 分钟前
单北斗GNSS变形监测系统安装与应用解析,提升位移监测精度
前端
J***Q29228 分钟前
前端微前端框架原理,qiankun源码分析
前端·前端框架
十一.36628 分钟前
66-69 原型对象,toString(),垃圾回收
开发语言·javascript·原型模式
菜鸟‍28 分钟前
【前端学习】React学习【万字总结】
前端·学习·react.js
百***844535 分钟前
Webpack、Vite区别知多少?
前端·webpack·node.js
Mintopia39 分钟前
零信任架构下的 WebAIGC 服务安全技术升级方向
前端·人工智能·trae