ajax调后台servlet,把返回json用vue做绑定

本文介绍如何将Vue.js与servlet、bootstrap及jquery等技术整合,实现数据绑定和展示。通过具体步骤展示了从前端页面搭建到后端数据交互的全过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 描述
最近项目需要开发微信手机端,本来用的架构是bootstrap+jquery,但每次数据绑定前台的时候jquery都把javascript代码和html代码混着写,违背业务与界面相分离的原则,希望找个轻量级的数据绑定js架构,觉得vue.js是个不错的选择,这里做个小demo把servlet+bootstrap+jquery+vue整合在一起。

2. 所需jar包

3. 项目结构
项目结构

4. 创建servlet

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>VueDatagrid</display-name>
  <servlet>
    <description></description>
    <display-name>LoadDataServlet</display-name>
    <servlet-name>LoadDataServlet</servlet-name>
    <servlet-class>com.vue.datagrid.LoadDataServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoadDataServlet</servlet-name>
    <url-pattern>/LoadDataServlet.do</url-pattern>
  </servlet-mapping>
</web-app>

5. 编写servlet代码

package com.vue.datagrid;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


public class LoadDataServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public LoadDataServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8;pageEncoding=UTF-8");
        response.setCharacterEncoding("UTF-8");

        Goods goods1 = new Goods();
        goods1.setId("1");
        goods1.setBarcode("101");
        goods1.setName("中华面粉");
        goods1.setShortName("面粉");

        Goods goods2 = new Goods();
        goods2.setId("2");
        goods2.setBarcode("102");
        goods2.setName("中华面包");
        goods2.setShortName("面包");

        Goods goods3 = new Goods();
        goods3.setId("3");
        goods3.setBarcode("103");
        goods3.setName("中华面条");
        goods3.setShortName("面条");

        List<Goods> goodList = new ArrayList<Goods>();
        goodList.add(goods1);
        goodList.add(goods2);
        goodList.add(goods3);

        PrintWriter out = response.getWriter();  

        try {
            String json = JSONObject.toJSONString(goodList);
            System.out.println("json:" + json);
            out.write(json);  
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.flush();
            out.close();
        }
    }

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

}

6. 编写页面代码
页面代码有个坑,弄了很久才弄出来,但还是不知所以然。在ajax调用后台servlet时,已经设置了datatype:”json”,但servlet的printwriter处理后response的仍然是“text”,需要在success后加上JSON.parse(data)把字符串转成JSON类型,希望有哪位大神可以告诉缘由和告诉我怎么可以response JSON类型到前台。

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Vue Bind Data</title>
<link rel="stylesheet" type="text/css" href="https://cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/vue/latest/vue.js"></script>
<script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script>
<script src="js/vue-async-data.js"></script>
</head>
<body>
    <div class="container">
        <div class="col-md-6 col-md-offset-3">
            <h1>Vue demo</h1>
            <div id="app">
                <button v-on:click="nameSearch()">查询</button><br><br>
                <table>
                    <thead>
                    <tr>
                        <th style='width:3%; text-align: left'>ID</th>
                        <th style='width:5%; text-align: left'>名称</th>
                        <th style='width:10%; text-align: left'>条形码</th>
                        <th style='width:10%; text-align: left'>简称</th>
                    </tr>
                    </thead>
                    <tbody>
                        <tr v-for="goods in goodsList" track-by="$index">
                            <td>{{goods.id}}</td>
                            <td>{{goods.name}}</td>
                            <td>{{goods.barcode}}</td>
                            <td>{{goods.shortName}}</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</body>
<script>
$(function() {
    $.ajax({
        type:'get',
        url:'http://localhost:8080/VueDatagrid/LoadDataServlet.do',
        success: function(data){
            if (data.success){
                pushDom(data);
            }else{
                alert("接口调用失败");
            }
        },
        error: function(data){
            alert(JSON.stringify(data));
        }
    });

    function pushDom(data){
        // 然后再交给 vue 进行渲染
        var vm = new Vue({
            el: '#app',
            data: data
        });
    }
})
</script>
</html>

7. 运行程序

在浏览器打开地址 http://localhost:8080/VueDatagrid/index2.jsp,效果图如下
效果图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值