jQuery 调用 Ajax 实现查询的局部更新 (jsp + servlet + jQuery + Ajax)

前端展示界面如下图所示,源代码见 ajaxDemo.jsp。

ajaxDemo.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta charset="UTF-8">
    <title>jQuery 调用 Ajax 实现查询的局部更新</title>
</head>
<body>

查询信息:<input type="text" name="info" id="info">
<input type="submit" id="search"> <br>
<span id="show"></span>

<!-- 引入jQery -->
<script src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
    $(function(){
        // 点击按钮触发
        $("#search").click(function() {
            var value = $("#info").val();
            // 使用ajax发送请求
            $.ajax({
                type: 'POST', // 请求类型, 默认为 GET
                url: "TestAjaxServlet", // 	必需。规定把请求发送到哪个 URL。
                data: "info="+value, // 可选。映射或字符串值。规定连同请求发送到服务器的数据。
                success: function(result){ // 可选。请求成功时执行的回调函数。
                    // 展示结果
                    $("#show").html(result);
                }
            })
        });
    })
</script>
</body>
</html>

servlet 源文件,TestAjaxServlet.java

package com.syrdbt.system.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/TestAjaxServlet")
public class TestAjaxServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        String name = request.getParameter("info");

        System.out.println("开始处理信息 " + name);

        // 判断信息,将结果返回到前端
        if(name.equals("abc")) {
            response.getWriter().print("success");
        } else {
            response.getWriter().print("failed");
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}

测试结果截图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值