jsp变量作为javascript函数参数

时间:2014-12-16 01:23:43

标签: java javascript spring jsp

我在使用jsp变量作为javascript参数时遇到了麻烦。

javascript函数:

function user(name, lastname, nick) {
    return name + " " + lastname + " (" + nick + ")";
}

在jsp中使用它:

<tbody>
<c:forEach var="et" items="${eTestsToAdd}">
    <tr>
        <td><script>document.write(user(${et.author.name}, ${et.author.lastname}, ${et.author.nick}));</script></td>

它也适用于另一个例子:

JS

function parseToDate(dateInMiliseconds) {
    var d = new Date(dateInMiliseconds);
    var string = d.getDay().toString() + "-" + d.getMonth().toString() + "-" + d.getFullYear().toString();
    return string;
}

JSP

<script>document.write(parseToTime(${uc.startDate.time}));</script>

有两个不同,工作示例是带有一个参数的javascript函数,参数是int,而不工作的是带有三个字符串参数的javasript函数。如何传递这些值才能使其正常工作? 没有小脚本请:)

// EDIT

好吧,我会尝试更多地澄清一下:

我在jsp中有一个表,其中显示了一些数据:

<tbody>
    <c:set var="i" value="0" />
    <c:forEach var="uc" items="${userClasses}">
        <c:set var="i" value="${i+1}" />
        <c:url var="usrURL" value="/users/show/${uc.user.nick}" />
        <tr onclick="location.href = '${usrURL}' ">
            <td>${i}</td>
            <td><img class="img-circle img-little" src="<c:url value='/imageView/${uc.user.avatar.id}'/>" />
                <script>document.write(user(${uc.user.name}, ${uc.user.lastname}, ${uc.user.nick}));</script>
            </td>
            <td><script>document.write(parseToTime(${uc.startDate.time}));</script></td>
        </tr>
                                </c:forEach>
                            </tbody>

uc.user - 是用户实体,我想在模式表中很好地编写它 -

名称姓氏(userName)

我在这里发布了javascript。 但是当我在jsp中使用这个函数时,tomcat会抛出org.apache.jasper.JasperException:在我调用js函数的行处理JSP页面时发生异常。显然,我在某种程度上在jsp中错误地使用它;不过,我对javascripts很满意。我的问题是如何在这里正确使用这个javasript函数?

1 个答案:

答案 0 :(得分:1)

我不确定这是解决方案而不知道eTestsToAdd集合的值是什么,但这肯定是一个问题。

鉴于此代码snipplet:

document.write(user(${et.author.name}, ${et.author.lastname}, ${et.author.nick}));

作者的值分别是joeshmoejs这会导致此输出

document.write(user(joe, shmoe, js));

这是无效的javascript,JS评估者会查找名为joe,schome和js的变量。您需要将输出包装在引号中。

document.write(user("${et.author.name}", "${et.author.lastname}", "${et.author.nick}"));

现在如果有人为名字加上名字lovemesome"XXS,你也会收到javascript错误。您将需要清理输出变量,您可以使用以下方法对此情况执行此操作:

${fn:replace(${et.author.name}, '\"', '\\\"'}
相关问题