我正在尝试使用 .jsp 从 MySQL 数据库接收数据,将该数据放入数组中,然后将该数组发送到 javascript 并使用该数组填充通过 d3.js 制作的图表。我已经对如何执行 .jsp 部分进行了一些研究,但它对我来说并没有多大意义。我也几乎没有发现任何关于从 java 到 javascript 的信息。这是我目前拥有的:
<%@ page language="java" import="java.sql.*"%>
<html>
<head>
<title>D3 Test</title>
<script type="text/javascript" src="d3/d3.v2.js"></script>
<style type="text/css">
</style>
</head>
<body>
<%
Connection con=null;
ResultSet rst=null;
Statement stmt=null;
try{
String url="jdbc:mysql://localhost:3306/usermaster? user=root&password=7rubA5Ra";
int i=1;
con=DriverManager.getConnection(url);
stmt=con.createStatement();
rst=stmt.executeQuery("select * from test ");
%>
<script type="text/javascript">
var dataset = [ 7, 12, 15, 21, 23, 27, 24, 20, 17, 15,
12, 14, 17, 22, 20, 19, 18, 20, 25, 27 ];
var w = 500;
var h = 100;
var barPadding = 1;
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("id", "rect1")
.attr("x", function(d, i) {
return i * (w / dataset.length);
})
.attr("y", function(d) {
return h - d*4;
})
.attr("width", w/ dataset.length - barPadding)
.attr("height", function(d) {
return d * 4;
})
.attr("fill", function(d) {
return "rgb(0, 0, " + (d * 10) + ")";
});
/*svg.selectAll("rect")
.data(dataset2)
.enter()
.append("rect")
.attr("id", "rect2")
.attr("x", function(d, i) {
return i * (w / dataset2.length);
})
.attr("y", function(d) {
return h - d*4;
})
.attr("width", w/ dataset2.length - barPadding)
.attr("height", function(d) {
return d * 4;
})
.attr("fill", function(d) {
return "rgb(0, 100, " + (d * 10) + ")";
});*/
svg.selectAll("text")
.data(dataset)
.enter()
.append("text")
.text(function(d) {
return d;
})
.attr("x", function(d, i) {
return i * (w / dataset.length) + 5;
})
.attr("y", function(d) {
return h - (d * 4) + 15;
})
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("fill", "white");
</script>
</body>
我真的只需要有人为我指明正确的方向。我希望将数据库中的信息放入变量数据集中。
谢谢, 空盒子
最佳答案
在要将其嵌入到 JavaScript 中的位置周围添加 JSP 标记。
var dataset = [
<% while (rst!=null && rst.next()) { %>
<%=rst.getInt("<column name>")%>,
<% } %>
];
关于java - 使用 MYSQL 和 JSP 填充 Javascript 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10708250/