前端用Ajax获取servlet后端数据

前期工作掌握:

  • 创建JavaWeb项目
  • 导入maven依赖
  • mybatis连接数据库(注意MVC分层)
  • 配置tomcat(设置一下热部署,比较方便)

之后的servlet内容(实现了sql一个比较简单的查询语句)

@WebServlet("/Demo")
public class Servlet extends HttpServlet {
    String id;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        SqlSession session = mybatisUtils.getSession();
        BlogMapper mapper = session.getMapper(BlogMapper.class);
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //request通过参数名获取ajax传过来的值
        id = req.getParameter("id");
        Blog blog = mapper.searchBlog(id);
        //自动行刷新的缓冲字符输出流,特点是可以按行写出字符串,并且可以自动行刷新
        PrintWriter printWriter = resp.getWriter();
        //Gson 是 Google 提供的用来在 Java 对象和 JSON 数据之间进行映射的 Java 类库。可以将一个 JSON 字符串转成一个 Java 对象,或者反过来。
        String b = new Gson().toJson(blog);
        printWriter.write(b);
        printWriter.flush(); //清除输出的缓存
        printWriter.close();  //关闭输出
    }
}

前端内容

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>MyDemo</title>
    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js">
    </script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <script type="text/javascript">
       function a() {
           $.ajax({
               type:"GET",
               url:"http://localhost:8083/Demo",
               dataType:"json", //预期服务器返回数据的类型
               data:{"id":"47d06a4f30e44804b45db93c9cdf6a4d","name":"动态SQL"},//ajax所传参数
               success:function (response) {
                   console.log(response)
                   document.getElementById("myDiv1").innerText=response.name
                   $("#myDiv1").innerHTML=response.author;
               }
           })
       }
    </script>
</head>
<body>
<div id="myDiv"><h2 id="myDiv1">通过ajax改变我的文本内容</h2></div>
<button id="testAjax" type="button" onclick="a()">点我点我点我</button>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值