【问题标题】:How to pass a model property to a javascript function in JSP which itself returns a value如何将模型属性传递给 JSP 中的 javascript 函数,该函数本身返回一个值
【发布时间】:2017-07-25 12:24:01
【问题描述】:

我必须在 jsp 页面本身中格式化从控制器 [Spring] 收到的日期。
这是 JSP 文件:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

<!DOCTYPE html>
<html lang="en">

<head>

<script
src="${pageContext.request.contextPath}/static/js/custom/customer.js">/script>
</head>
<body>

                <table id="success-story">
                    <thead>
                        <tr>
                            <th width="5%">Sl#</th>
                            <th width="50%">Description</th>
                            <th width="10%">Status</th>
                            <th width="30%">Created on</th>
                            <th width="5%">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <c:forEach items="${customer.rfqs}" var="v" varStatus="count">
                            <tr>
                                <td>${count.count}</td>
                                <td>${v.description}</td>
                                <td>${v.status}</td>
                                <td>$v.createdTs</td>
                                <td align="center">
                                   <a href="#" onclick="view(${v.requestId})"> view</a>
                                   <a href="#" onclick="edit(${v.requestId})">edit</a>
                                </td>
                            </tr>
                        </c:forEach>
                    </tbody>
                </table>

  </body>
 </html>'

${v.createdTS} 返回格式为 YYYY:MM:DD HH:MM:SS 的时间戳
现在我必须将此时间戳转换为这种格式 DD:MM:YYYY
但它只能在填充行时在前端完成,怎么做?

我尝试了许多可能的解决方案,但没有一个有效,这是我在 JS 文件中的功能

customer.js:

function formatDate(date) {
  var monthNames = [
    "Jan", "Feb", "Mar",
    "Apr", "May", "Jun", "Jul",
    "Aug", "Sep", "Oct",
    "Nov", "Dec"
  ];

  var day = date.getDate();
  var monthIndex = date.getMonth();
  var year = date.getFullYear();

  return day + ' ' + monthNames[monthIndex] + ' ' + year;
}

我能否以某种方式使用此功能,或者任何其他替代方法都适合我。我只需要转换。
提前谢谢

【问题讨论】:

    标签: javascript java html jsp spring-mvc


    【解决方案1】:

    如果 createdTs 属性是日期对象 - 您可以使用 fmt tag

    <fmt:formatDate pattern = "yyyy-MM-dd" value = "${v.createdTs}" />
    

    如果是String类型,可以在服务器端格式化。

    【讨论】:

    • 记得还要像这样指定taglib uri &lt;%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %&gt;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-18
    • 1970-01-01
    相关资源
    最近更新 更多