ITPub博客

首页 > IT职业 > IT生活 > JavaScript系列:ajax异步加载jqgrid之动态创建

JavaScript系列:ajax异步加载jqgrid之动态创建

IT生活 作者:阿迪 时间:2021-09-09 09:17:18 0 删除 编辑
  • 前言
    之前写过一篇过于ajax异步加载jqgrid的文章,那个只是一个特殊的情况,如果创建不同数据库表的jqgrid,必须分别写servlet,dao层和连接池,很麻烦,今天我写了一个万能的写法,客官只要在前台js中写入表格名称和字段名称即可实现功能!
    下面就是代码实例,关于jqgrid,ajax的介绍这里暂时不多说,有不懂的可以参考我之前的文章!
  • 代码实例
  • jsp



    
定义>类型





定义>类型
已定义模拟量测点信息
  • js
;(function($){
    $.fn.jqGridTypeDefine = function(options){
        //获取jquery对象
        var grid_selector = this;
        var initDate = "{oper: ""," +
                        "height: ""," +
                        "width: ""," +
                        "pager_selector: "typeDefinePager"," +
                        "where: ""," +
                        "wherestring: {}," +
                        "fileds: ["id", "property", "name", "sensortype", "unit","highvalue"]," +
                        "table:"kj_typedefine"}";
        $.ajax({
            url:"MyServlet",
            async:true,   //是否为异步请求
            cache:false,  //是否缓存结果
            type:"GET",
            dataType:"json",
            data :{
                "data" : initDate,
            },
            success : function(data){
                for(var i=0;i
  • servlet
package com.test.servlet;

import com.test.entity.MyEntity;
import com.test.service.MyService;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MyServlet extends HttpServlet {
    MyService service = new MyService();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
        response.setContentType("text/html");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
        response.setContentType("text/html");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String jqgridData = request.getParameter("data");
        MyEntity myEntity = new MyEntity();
        myEntity.setJqgridData(jqgridData);
        String str = service.getJqgridData(myEntity);
        response.getWriter().print(str);
    }
}
  • service
package com.test.service;

import com.test.dao.MyDao;
import com.test.entity.MyEntity;

public class MyService {
    MyDao myDao = new MyDao();
    public String getJqgridData(MyEntity myEntity) {
        String jqgridData = myDao.selectJqgridData(myEntity);
        return jqgridData;
    }
}
  • dao
package com.test.dao;

import com.test.entity.MyEntity;
import com.test.entity.SecondData;
import com.test.util.MySQLFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MyDao {

    public String selectJqgridData(MyEntity myEntity) {
        String str = myEntity.getJqgridData();
        String data = "";
        try {
            JSONObject obj = new JSONObject(str);
            String oper = String.valueOf(obj.get("oper"));
            String fileds = String.valueOf(obj.get("fileds")).replace(""","")
                                                              .replace("[","")
                                                              .replace("]","");
            String table = String.valueOf(obj.get("table"));
            String sql = String.format(
                    "select %s from %s ",fileds,table
            );
            System.out.println(sql);
            data = MySQLFactory.queryData(sql);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return data;
    }
}
  • entity
package com.test.entity;

public class MyEntity {
    private String jqgridData;

    public MyEntity() {
    }

    public MyEntity(String jqgridData) {
        this.jqgridData = jqgridData;
    }

    public String getJqgridData() {
        return jqgridData;
    }

    public void setJqgridData(String jqgridData) {
        this.jqgridData = jqgridData;
    }
}
  • 连接池(我用的mysql数据库)
package com.test.util;

import java.sql.*;

public class MySQLFactory {
    static final String DRVIER = "com.mysql.jdbc.Driver";
    static final String URL = "jdbc:mysql://localhost:3306/mysql";
    static final String USERNAMR = "root";
    static final String PASSWORD = "root";

    private static Connection conn = null;
    public static Connection getConnection(){
        try {
            Class.forName(DRVIER);
            conn = DriverManager.getConnection(URL, USERNAMR, PASSWORD);
            System.out.println("成功连接数据库");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("class not find !", e);
        } catch (SQLException e) {
            throw new RuntimeException("get connection error!", e);
        }
        return conn;
    }

    public static void executeSQL(String sql) {
        Statement stat = null;
        try {
            conn = getConnection();
            stat = conn.createStatement();
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        try {
            stat.execute(sql);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        try {
            if (stat != null) stat.close();
            if (conn != null) conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String queryNoPage(String sql) {
        Connection conn      = null;
        Statement  stat      = null;
        ResultSet  rows      = null;
        StringBuffer   buff = new StringBuffer();
        try {
            conn   =  getConnection();
            stat   =  conn.createStatement();
        }
        catch (Exception e) {
            e.printStackTrace();
            return "[]";
        }
        try {
            rows    = stat.executeQuery(sql);
            //得到数据集的列数
            ResultSetMetaData rsmd = rows.getMetaData();
            int    colCount      = rsmd.getColumnCount();
            boolean first = true;
            buff.append("[");
            while (rows.next()) {
                String rowStr  = "";
                for (int i = 1; i 1) rowStr += ",";
                    String tempValue   =  rows.getString(i);
                    rowStr          += String.format("%s", tempValue);
                }
                rowStr = String.format(""%s"", rowStr);
                if (first) first = false;
                else buff.append(",");
                buff.append(rowStr);
            }
            buff.append("]");
        }catch (Exception e) {
            e.printStackTrace();
            return "[]";
        }finally {
            try {
                rows.close();
                stat.close();
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return buff.toString();
    }

    public static String queryData(String sql){
        Connection conn      = null;
        Statement  stat      = null;
        ResultSet  rows      = null;
        StringBuffer   buff = new StringBuffer();
        try {
            conn   =  getConnection();
            stat   =  conn.createStatement();
        }
        catch (Exception e) {
            e.printStackTrace();
            return "[]";
        }
        try {
            rows    = stat.executeQuery(sql);
            //得到数据集的列数
            ResultSetMetaData rsmd = rows.getMetaData();
            int    colCount      = rsmd.getColumnCount();
            buff.append("[");
            while (rows.next()) {
                String rowStr  = "";
                buff.append("{");
                for (int i = 1; i 1) rowStr += ",";
                    String name = rsmd.getColumnName(i);
                    String tempValue   =  rows.getString(i);
                    rowStr          += String.format(""%s":"%s"", name,tempValue);
                }
                rowStr = String.format("%s", rowStr);
                buff.append(rowStr);
                buff.append("},");
            }
            buff.append("]");
        } catch (SQLException e) {
            e.printStackTrace();
            return "[]";
        }
        String str = buff.toString().replace(",]","]");
        return str;
    }
}

  • 效果展示
    图片描述

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2038/viewspace-2809274/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-04-16

  • 博文量
    0
  • 访问量
    482