ajax异步加载查询数据库

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>数据</title>
        <link rel="stylesheet" href="static/css/style.css" type="text/css">
        <!-- jQuery-easyUI start -->
        <link rel="stylesheet" type="text/css" href="https://www.jeasyui.com/easyui/themes/default/easyui.css">
        <link rel="stylesheet" type="text/css" href="https://www.jeasyui.com/easyui/themes/icon.css">
        <link rel="stylesheet" type="text/css" href="https://www.jeasyui.com/easyui/themes/color.css">
        <link rel="stylesheet" type="text/css" href="https://www.jeasyui.com/easyui/demo/demo.css">
        <script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
        <script type="text/javascript" src="https://www.jeasyui.com/easyui/jquery.easyui.min.js"></script>
        <!-- jQuery-easyUI end -->
        <script type="text/javascript">
            document.createElement("section");
            document.createElement("article");
            document.createElement("footer");
            document.createElement("header");
            document.createElement("hgroup");
            document.createElement("nav");
            document.createElement("menu");
        </script>
        <script type="text/javascript">
            function Save() {
                document.getElementById("PageOfficeCtrl1").WebSave();
            }
        </script>
    </head>
    <body>
        <header>
            <div class="w12 header">
                <a class="db logo fl"><img src="static/images/logo.jpg"
                    width="327" height="94" alt="" />
                </a>
                <div class="fr logofr">
                    <a href="#" class="blk">返回首页</a> |<a href="#" class="blk">客服中心</a><br>
                    如注册遇到问题请拨打:<strong style="font-size:14px;">400-000-0000</strong>
                </div>
            </div>
        </header>
        <div class="head_border"></div>
        <section class="w12 login"> <em class="fr">当前用户:张三 </em> </section>
        <section class="main w12">
            <div class="title">
                <a class="title1 db fl">审核报告</a><a class="title2 db fl">审核合同</a>
            </div>
            <div class="fr tit2">
                <span class="arr"></span>
            </div>
        </section>
        <br /><br />

        <div style="text-align:content;margin-left: 300px;">
            <table id="dg" title="北京某某科技有限公司" class="easyui-datagrid" style="width:700px;height:250px;,margin: auto;"
                    url="get_users.php" toolbar="#toolbar" pagination="true" rownumbers="true" fitColumns="true" singleSelect="true">
                <thead>
                    <tr id="insertSpareEpt">
                        <th field="firstname" width="50">单位编号</th>
                        <th field="lastname" width="50">单位名称</th>
                        <th field="phone" width="50">单位性质</th>
                        <th field="email" width="50">单位地址</th>
                    </tr>
                </thead>
            </table>
        </div>

        <div id="toolbar">
            <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="newUser()">添加</a>
            <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editUser()">修改</a>
            <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="destroyUser()">删除</a>
        </div>
        <div id="divTab"></div>
        <!-- 弹窗 -->
        <div id="dlg" class="easyui-dialog" style="width:400px" data-options="closed:true,modal:true,border:‘thin‘,buttons:‘#dlg-buttons‘">
            <form id="fm" method="post" novalidate style="margin:0;padding:20px 50px">
                <h3>单位信息</h3>
                <div style="margin-bottom:10px">
                    <input name="firstname" class="easyui-textbox" required="true" label="单位编号:" style="width:100%">
                </div>
                <div style="margin-bottom:10px">
                    <input name="lastname" class="easyui-textbox" required="true" label="单位名称:" style="width:100%">
                </div>
                <div style="margin-bottom:10px">
                    <input name="phone" class="easyui-textbox" required="true" label="单位性质:" style="width:100%">
                </div>
                <div style="margin-bottom:10px">
                    <input name="email" class="easyui-textbox" required="true" validType="email" label="单位地址:" style="width:100%">
                </div>
            </form>
        </div>
        <div id="dlg-buttons">
            <a href="javascript:void(0)" class="easyui-linkbutton c6" iconCls="icon-ok" onclick="saveUser()" style="width:90px">添加</a>
            <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$(‘#dlg‘).dialog(‘close‘)" style="width:90px">取消</a>
        </div>

        <script type="text/javascript">
            var url;
            function newUser(){
                $(‘#dlg‘).dialog(‘open‘).dialog(‘center‘).dialog(‘setTitle‘,‘New User‘);
                $(‘#fm‘).form(‘clear‘);
                url = ‘save_user.php‘;
            }
            function editUser(){
                var row = $(‘#dg‘).datagrid(‘getSelected‘);
                if (row){
                    $(‘#dlg‘).dialog(‘open‘).dialog(‘center‘).dialog(‘setTitle‘,‘Edit User‘);
                    $(‘#fm‘).form(‘load‘,row);
                    url = ‘update_user.php?id=‘+row.id;
                }
            }
            function saveUser1(){
                $(‘#fm‘).form(‘submit‘,{
                    url: saveInfo,
                    onSubmit: function(){
                        return $(this).form(‘validate‘);
                    },
                    success: function(result){
                        var result = eval(‘(‘+result+‘)‘);
                        if (result.errorMsg){
                            $.messager.show({
                                title: ‘Error‘,
                                msg: result.errorMsg
                            });
                        } else {
                            $(‘#dlg‘).dialog(‘close‘);        // close the dialog
                            $(‘#dg‘).datagrid(‘reload‘);    // reload the user data
                        }
                    }
                });
            }

            /* 保存  */
            function saveUser(){
                var info;
                var firstname = $("input[name=‘firstname‘]").val();
                var lastname = $("input[name=‘lastname‘]").val();
                var phone = $("input[name=‘phone‘]").val();
                var email = $("input[name=‘email‘]").val();
                $.ajax({
                    type : ‘get‘,
                    url : ‘saveInfo‘,
                    data:{
                        "firstname":firstname,
                        "lastname":lastname,
                        "phone":phone,
                        "email":email
                    },
                    cache : false,
                    async : false,
                    dataType : ‘json‘,
                    success : function(data){
                        $("#dg").datagrid("loadData",data);// 数据加载jQuery easyUI表格中

                    /* var tabStr = "";
                    $.each(data, function(index,value){
                        var item = data[index];
                        var itemFirstname = item.firstname;
                        var itemLastname = item.lastname;
                        var itemPhone = item.phone;
                        var itemEmail = item.email;
                        var itemStr = "<table border=‘1‘ cellpadding=‘0‘ cellspacing=‘0‘><tr>"+
                                      "<td name=‘firstname‘ width=50>"+itemFirstname+"</td>"+
                                      "<td name=‘lastname‘ width=50>"+itemLastname+"</td>"+
                                       "<td name=‘phone‘ width=50>"+itemPhone+"</td>"+
                                       "<td name=‘email‘ width=50>"+itemEmail+"</td>"+
                                  "</tr></table>";
                            tabStr += itemStr;
                    })
                    document.getElementById("divTab").innerHTML = tabStr; */

                    } , error:function(data){
                        alert("加载数据失败!"+data);
                    }
                });
                // 关闭添加窗口
                $(‘#dlg‘).dialog(‘close‘);
            }

            function destroyUser(){
                var row = $(‘#dg‘).datagrid(‘getSelected‘);
                if (row){
                    $.messager.confirm(‘Confirm‘,‘Are you sure you want to destroy this user?‘,function(r){
                        if (r){
                            $.post(‘destroy_user.php‘,{id:row.id},function(result){
                                if (result.success){
                                    $(‘#dg‘).datagrid(‘reload‘);    // reload the user data
                                } else {
                                    $.messager.show({    // show error message
                                        title: ‘Error‘,
                                        msg: result.errorMsg
                                    });
                                }
                            },‘json‘);
                        }
                    });
                }
            }
        </script>
    </body>
</html>

package com.wyebd.controller;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import com.wyebd.bean.Contract;
import com.zhuozhengsoft.pageoffice.OpenModeType;
import com.zhuozhengsoft.pageoffice.PageOfficeCtrl;
import com.zhuozhengsoft.pageoffice.wordwriter.WordDocument;

@RestController
public class ReadDataController {

    private static Logger log = Logger.getLogger(ReadOnlyController.class);
    private final String DB_URL = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8";
    private static final String USER = "root";
    private static final String PASS = "root";
    private static Connection con = null;
    private static PreparedStatement ps = null;
    private static Statement stmt = null;
    private static ResultSet rs = null;

    /**
     * 跳转至查询页面
     * @param request
     * @param response
     * @param map
     * @return
     */
    @RequestMapping(value = "/readData", method = RequestMethod.GET)
    public ModelAndView readData() {
        ModelAndView mv = new ModelAndView("readData");
        return mv;
    }

    /**
     * 保存
     * @param request
     * @param response
     * @param map
     * @return
     */
    @RequestMapping("saveInfo")
    public String saveInfo(HttpServletRequest request, HttpServletResponse response, Map<String, Object> map) {
        List<Contract> list = new ArrayList<Contract>();
        String firstname = request.getParameter("firstname");
        String lastname = request.getParameter("lastname");
        String phone = request.getParameter("phone");
        String email = request.getParameter("email");
        String json = null;
        int id = 0;
        try {
            getConnection();
            ps = con.prepareStatement("insert into test values (?,?,?,?,?)");
            ps.setInt(1, id);
            ps.setString(2, firstname);
            ps.setString(3, lastname);
            ps.setString(4,phone);
            ps.setString(5, email);
            ps.executeUpdate();
            log.info("添加成功");
            rs = stmt.executeQuery("select * from test");
            while(rs.next()){
                Contract con = new Contract();
                con.setFirstname(rs.getString("firstname"));
                con.setLastname(rs.getString("lastname"));
                con.setPhone(rs.getString("phone"));
                con.setEmail(rs.getString("email"));
                list.add(con);
            }
            // list转为json传入前端
            json = JSON.toJSONString(list);
            log.info(json);
            // 取得流向JSP传递数据
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().println(json);
            response.reset();
        } catch (Exception e) {
            log.info("SQLException: " + e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                ps.close();
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
         return json;
    }

    /**
     * 连接数据库
     * @throws ClassNotFoundException
     * @throws SQLException
     */
    public void getConnection() throws ClassNotFoundException, SQLException {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection(DB_URL, USER, PASS);
            stmt = con.createStatement();
        } catch (Exception e) {
            System.out.println("SQLException: " + e.getMessage());
            e.printStackTrace();
        }
    }

}

原文地址:https://www.cnblogs.com/hongwei2085/p/9058535.html

时间: 2024-09-29 08:52:40

ajax异步加载查询数据库的相关文章

淘宝购物车页面 智能搜索框Ajax异步加载数据

如果有朋友对本篇文章的一些知识点不了解的话,可以先阅读此篇文章.在这篇文章中,我大概介绍了一下构建淘宝购物车页面需要的基础知识. 这篇文章主要探讨的是智能搜索框Ajax异步加载数据.jQuery的社区非常的活跃,许多朋友都在不同地方分享了很多优秀的插件.我在相关的网站上找过想实现类似功能的插件,但是没有找到.于是乎,自己动手丰衣足食.自己来搭建智能搜索框下拉列表.当然,如果有类似功能并且常维护Bug的插件,望留言交流. 源码地址: 淘宝购物车页面--PC端和移动端项目实战 首先需要先给大家打一根

Ajax异步加载数据及Redis缓存

针对网页分类条目的动态加载,图为页面的Head部分. //categoryListServlet准备分类数据 ProductService service = new ProductService(); List<Category> categoryList = service.findAllCategoryList(); response.setContentType("text/html; charset=utf-8"); Gson gson = new Gson();

jQuery的AJax异步加载片段

主要用到load()方法以及getScript()方法,具体以一个例子说明: 在现有html文件中加载一个拟好的片段,以及在片段加载完成之前阻止用户进一步操作的弹出框. 首先是现有html代码,无任何内容: <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>AJax异步加载</title> <scri

ajax异步加载问题

使用ajax异步加载数据,在之后需要用到这个数据时,应该将之后的js一并写入ajax函数中,否则后面的js不能找到动态拼接的dom节点. 或者将其封装成方法,在ajax动态加载数据的最后调用该方法.

使用ajax异步加载数据

使用ajax异步加载数据 controller为User赋值 @RequestMapping("/a2") public List<User> a2() { List<User> userlist = new ArrayList<User>(); userlist.add(new User("大头儿子", 6, "男")); userlist.add(new User("小头爸爸", 30,

Ajax 异步加载

AJAX (Asynchronous JavaScript and XML,异步的 JavaScript 和 XML).它不是新的编程语言,而是一种使用现有标准的新方法,是在不重新加载整个页面的情况下与服务器交换数据并更新部分网页的艺术. 那么,让我们一起走进AJax的世界吧. 基础语法 获取Ajax对象 设置回调函数 readystate status 开启交互 客户端更新页面 实例体验 使用Servlet方式 AjaxServletjava webxml ajaxhtml 实验结果 使用JS

今日头条图片ajax异步加载爬取,并保存至mongodb,以及代码写法的改进

import requests,time,re,json,pymongofrom urllib.parse import urlencodefrom requests.exceptions import RequestExceptionfrom bs4 import BeautifulSoup as bs #连接mongodbclient = pymongo.MongoClient(host='localhost',port=27017)#指定数据库名称db = client.toutiao #

使用Ajax异步加载页面时,怎样调试该页面的Js

前言-本人不是干前端的,所以有的名词不专业 在前端中,有时候会遇到这样的框架,http://172.17.11.151:8060/frontend/backend.html#1.html (通过解析URL,把1.html异步加载到指定位置),不知道这样的框架叫什么名字. 那我们就会遇到一个问题,调试1.html的时候怎么办,通过浏览器掉出控制台找不到1.Html页面,无法加断点啊. 解决办法 在1.html 你所要调试位置加上一句代码  debugger;  就可以了,就是这么爽 可以调试了,可

Ajax异步加载

//第一步 使用@Expose查找 //实体类的属性名不一定与数据库列名相同,但是类型一定要匹配 //当使用gson进行生产json字符串时,可以通过判断是否有该注解生成字 符串内容 //如由注解就添加到字符串中,没有的就不添加到json字符串中 //说明:需要使用如下方式实例化gson对象:new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); @Expose private int id; @Expose priv