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>

运行结果

相关推荐
Mr Xu_3 分钟前
解决 Vue + Axios 热更新导致响应拦截器重复注册的问题
前端·javascript·vue.js
Coder_preston9 分钟前
JavaScript学习指南
开发语言·javascript·ecmascript
岁岁种桃花儿15 分钟前
NodeJs从入门到上天:什么是Node.js
前端·node.js
Jinuss16 分钟前
源码分析之React中Scheduler调度器的最小二叉堆
javascript·算法·react.js
a11177619 分钟前
电流卡片特效(html网页 开源)
javascript·css·css3
colicode19 分钟前
语音报警接口开发参考:紧急情况下快速调用语音API发送安全警报
前端·语音识别
狗都不学爬虫_20 分钟前
JS逆向 -最新版 盼之(decode__1174、ssxmod_itna、ssxmod_itna2)纯算
javascript·爬虫·python·网络爬虫·wasm
天天进步201521 分钟前
透明的可观测性:剖析 Motia Workbench 与插件系统架构
javascript
夏河始溢22 分钟前
一八四、Zustand 状态管理详解、与 Redux、MobX 的对比分析
前端·javascript·react.js·状态管理·zustand
wangmengxxw22 分钟前
设计模式 -详解
开发语言·javascript·设计模式