如何总结使用JavaScript从jsp数据库生成的html表的列? [英] how to sum columns of html table generated from database in jsp using javascript?

查看:41
本文介绍了如何总结使用JavaScript从jsp数据库生成的html表的列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在我的网站上工作,我想在一个jsp上使用javascript对html表的一列中的值求和.我发现各种代码可以添加已经放入的静态数据,但是当我在代码中使用相同的内容时,它将无法正常工作.

I am working on my site and i want to sum the values in one column of html table using javascript over a jsp. I have found various codes which can add static data which has been put in already but when i use same thing in my code it doesnt work.

javascript如下:-

The javascript is as follows:-

<script type="text/javascript">
var debugScript = true;

function computeTableColumnTotal(tableId, colNumber)
{       
  var result = 0;

  try
  {
    var tableElem = window.document.getElementById(tableId);           
    var tableBody = tableElem.getElementsByTagName("tbody").item(0);
    var i;
    var howManyRows = tableBody.rows.length;
    for (i=1; i<(howManyRows-1); i++) // skip first and last row (hence i=1, and howManyRows-1)
    {
       var thisTrElem = tableBody.rows[i];
       var thisTdElem = thisTrElem.cells[colNumber];            
       var thisTextNode = thisTdElem.childNodes.item(0);
       if (debugScript)
       {
          window.alert("text is " + thisTextNode.data);
       } // end if

       // try to convert text to numeric
       var thisNumber = parseFloat(thisTextNode.data);
       // if you didn't get back the value NaN (i.e. not a number), add into result
       if (!isNaN(thisNumber))
         result += thisNumber;
     } // end for

  } // end try
  catch (ex)
  {
     window.alert("Exception in function computeTableColumnTotal()\n" + ex);
     result = 0;
  }
  finally
  {
     return result;
  }

}

function finishTable()
{
  if (debugScript)
    window.alert("Beginning of function finishTable");

    var tableElemName = "hikeTable";
        //idhar column define kar raha hai wo
  var totalMilesPlanned = computeTableColumnTotal("hikeTable",2);
  var totalMilesHiked = computeTableColumnTotal("hikeTable",3);

    try 
  {
    var totalMilesPlannedElem = window.document.getElementById("totalMilesPlanned");
    document.getElementById("total_1").innerHTML = totalMilesPlanned;
    var totalMilesHikedElem = window.document.getElementById("totalMilesHiked");
    document.getElementById("total_2").innerHTML = totalMilesHiked ;

   }
   catch (ex)
   {
     window.alert("Exception in function finishTable()\n" + ex);
   }

   return;
}
</script>

这在html表格像

<html>
<body onload="finishTable();">
<tbody>
<table  id="hikeTable" align="center" border="1" bordercolor="lightslategray">
   <tr>
      <th scope="col">Locations</th>
      <th scope="col"> Date </th>
      <th >Miles (planned)</th>
      <th>Miles (actual)</th>

    </tr>
    <tr>
      <td>Alapocas Woods </td>
      <td>02/18/06</td>
      <td>1324</td>
      <td>1</td>

    </tr>

<tr>
      <td>Alapocas </td>
      <td>02/18/06</td>
      <td>1176576523</td>
      <td>23</td>

    </tr>

<tr>
      <td>Alapocas </td>
      <td>02/18/06</td>
      <td>67</td>
      <td>98</td>
    </tr>
<tr>
      <td colspan="2">Total </td>   
      <td id="total_1"></td>
      <td id="total_2"></td>
    </tr>
</tbody>
<table>
</html>

但是我的桌子是这样的:-

But my table is something like this :-

<html>
<body onload="finishTable();">
<tbody>
<table  id="hikeTable" align="center" border="1" bordercolor="lightslategray">
   <tr>
      <th scope="col">Locations</th>
      <th scope="col"> Date </th>
      <th >Miles (planned)</th>
      <th>Miles (actual)</th>

    </tr>
<%Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:dir","hr","hr");
java.sql.Statement statement = conn.createStatement();
java.sql.ResultSet rs = statement.executeQuery(searchquery);

while(rs.next()){
int buildarea = rs.getInt("build_area");
int numberoflevels = rs.getInt("no_of_levels");
%>
    <tr>
      <td>Alapocas Woods </td>
      <td>02/18/06</td>
      <td><%=buildarea%></td> //here a value comes from database
      <td>1</td>

    </tr>

<tr>
      <td>Alapocas </td>
      <td>02/18/06</td>
      <td>bumberoflevels</td>
      <td>23</td>

    </tr>


      <td colspan="2">Total </td>   
      <td id="total_1"></td>
      <td id="total_2"></td>
    </tr>
</tbody>
<%}%>
<table>
</html>

请帮助!

推荐答案

无论您是要使用servlet还是在JSP中进行数据库调用,我都交给您.流量几乎相同.

I leave it to you on whether you want to do the database calls using a servlet or in the JSP itself. The flow is almost the same.

首先,您创建一个用于表示UI上的数据的类.您有一组(位置,日期,计划里程和实际里程),然后共有它们.

First you create a class for representing the data on the UI. You have a set of (Location, Date, Planned Miles and Actual miles) and then a total of them.

您可能想要创建一个表示该类的类(我已经从HTML的id组成了这个名称,您可能希望提供一个更好的名称):

You may want to create a class to represent this (I have made up the name from the id of the HTML, you may want to give a better name):

class Hike
{
    private String location;
    private Date date;
    private Integer builtArea;
    private Integer numberOfLevels;
    //And their getters and setters
}

还有一个HikeData类

And a HikeData class

class HikeData
{
    private List<Hike>;
    private Integer totalBuiltArea;
    private Integer totalNumberOfLevels;
    //And their getters and setters
}

//数据库调用部分很好:

//The database call part is fine:

<%Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager
                  .getConnection("jdbc:oracle:thin:@localhost:1521:dir","hr","hr");
java.sql.Statement statement = conn.createStatement();
java.sql.ResultSet rs = statement.executeQuery(searchquery);

//Fetch the data and populate the above classes
int totalBuiltArea = 0;
int totalNumberOfLevels = 0;
List<Hike> hikeList = new ArrayList<Hike>();
while(rs.next()){
    Hike hike = new Hike();

    hike.setLocation(rs.getString("location"));
    hike.setDate(rs.getDate("date")));

    int builtArea = rs.getInt("build_area");
    hike.setBuiltArea(builtArea);

    int numberOfLevels = rs.getInt("no_of_levels");
    hike.setNumberOfLevels(numberOfLevels);

    totalBuiltArea+= builtArea;
    totalNumberOfLevels += numberOfLevels;
    hikeList.add(hike);
}

HikeData hikeData = new HikeData();
hikeData.setHikeList(hikeList);
hikeData.setTotalNumberOfLevels(totalNumberOfLevels);
hikeData.setTTotalBuiltArea(totalBuiltArea);

//Add the class to request
request.setAttribute("hikeData", hikeData);

HTML表部分现在更简单:

The HTML table part is now simpler:

<table  id="hikeTable" align="center" border="1" bordercolor="lightslategray">
   <tr>
      <th scope="col">Locations</th>
      <th scope="col"> Date </th>
      <th >Miles (planned)</th>
      <th>Miles (actual)</th>

    </tr>
<%HikeData hikeData = request.getAttribute("hikeData");
for(Hike hike : hikeData.getHikeList())
{%>
<tr>
      <td><%=hike.getLocation()%></td>
      <td><%=hike.getDate()%></td>
      <td><%=hike.getBuiltArea()%></td> //here a value comes from database
      <td><%=hike.getnumberOfLevels()%></td>

</tr>
<%}>%>
<tr>

    <td colspan="2">Total </td>   
    <td id="total_1"><%=hikeData.getTotalNumberOfLevels()%></td>
    <td id="total_2"><%=hikeData.getTotalBuiltArea()%></td>
</tr>

如果使用的是servlet,则将数据库部分移到servlet或从servlet调用的服务类中.

If you are using a servlet, you move the database part to the servlet or to a service class that is called from the servlet.

如果您继续使用JSP,那么所有这些都在JSP本身中.

If you are continuing with the JSP, you have all these in the JSP itself.

我知道先添加到请求再进行检索是多余的,但我这样做是为了让您决定将其移出JSP,会更容易.

I know adding to request and then retrieving is kind of redundant but I have done so so that if you decide to move this out of the JSP, it is easier.

最后注:这绝对不是编写Web应用程序的最佳方法. frameworks 使您的工作更轻松,并且应用程序可维护和可扩展.对于controller(servlet)部分,您可以使用众所周知的 struts 框架,[Spring Web flow][2]或非常简单的框架 Apache Wicket . 对于业务逻辑部分,可以使用EJB3或 spring . 对于数据库访问,您可以使用休眠.

On a closing Note: This is definitely not the best way to write web apps. There are frameworks to make your job easier and the application maintainable and scalable. For the controller(servlet) part you can use the well known struts framework, [Spring Web flow][2], or the very simple Apache Wicket. For the business logic part, you can use EJB3 or spring. For database access you can use hibernate.

这些都不是强制性的,但是拥有至少一个MVC框架(而不是数据库和业务逻辑的东西)总是一件好事. Struts使您的生活变得很轻松.

None of this is mandatory, but it always good to have at least a MVC framework i not the database and business logic stuff. Struts makes your life very easy.

这篇关于如何总结使用JavaScript从jsp数据库生成的html表的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆