Jquery ajax 实现填报单元格自动更新
需求背景:
我们的自动计算已经提供了单元格数据简单运算的异步触发填充单元格的效果,在面对客户个性话的需求(比如数据库中取去关联性数据回填单元格)虽然不能一次性满足客户的需求,但我们也有较好的扩展性。以数据库中取关联数据回填单元格为例。
实现原理:
自动计算中我们已经可以把相关的运行结果回填到了单元格中,但数据库中的关联数据是没有办法通过简单的函数得到了,但我们这里可以借用下 自动计算回填的功能,只要我们能拿到数据库的关联值即可,至于另外一步取值我们可以利用ajax 来得到相关的数据。
操作步骤:
1. 用ajax 方式从数据库中取数
a)function Change_Select(name){
var value1;
$.ajax({
type: “POST”,
url: “<%=appmap%>/SelectServlet”,
dataType:”text”,
data : { name :name
},
async:false,
success: function(responseText){
value1=responseText;
alert(responseText);
// return responseText;
}
});
return value1;
}
Ajax 中用的到的SelectServlet 需要到web.xml 中声明调用Class
<servlet>
<servlet-name>SelectServlet</servlet-name>
<servlet-class>com.runqian.api.SelectServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SelectServlet</servlet-name>
<url-pattern>/SelectServlet</url-pattern>
</servlet-mapping>
2. 报表设计 自动计算 结合ajax取值 回填 单元格
3. 实现效果
表数据
页面效果分解动作
Ps com.runqian.api.SelectServlet Java代码如下
package com.runqian.api;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.runqian.report4.usermodel.Context;
public class SelectServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private String driver = “com.mysql.jdbc.Driver”;
private String url = “jdbc:mysql://localhost:3306/runqian”;
private String user = “root”;
private String passwd = “123″;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name= request.getParameter(“name”);
response.setContentType(“text/html”);
response.setHeader(“Cache-Control”, “no-cache”);
response.setCharacterEncoding(“UTF-8″);
PrintWriter out = response.getWriter();
StringBuffer currVal = new StringBuffer();
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try { Class.forName(driver);
conn=DriverManager.getConnection(url, user, passwd);
stmt = conn.createStatement();
String sql = “select context from empname where name = ‘”+name+”‘”;
rs = stmt.executeQuery(sql);
if (rs.next()) {
currVal.append(rs.getString(“context”));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
out.print(currVal.toString().trim());
out.flush();
out.close();
}
}