gpt4 book ai didi

java - jsp变量作为javascript函数参数

转载 作者:行者123 更新时间:2023-12-03 11:12:44 25 4
gpt4 key购买 nike

我在使用 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>

有两个区别,工作示例是具有一个参数且参数为 int 的 javascript 函数,而不工作示例是具有三个字符串参数的 javasript 函数。我如何传递这些值以使其正常工作?请不要使用脚本:)

//编辑

好的,我会尝试进一步澄清:

我在 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 - 是用户实体,我希望将其以模式很好地写在表格中 -

姓名(用户名)

使用我在此处发布的 javascript。但是当我在jsp中使用这个函数时,tomcat抛出org.apache.jasper.JasperException:在我调用js函数的行处理JSP页面时发生异常。很明显,我在 jsp 中使用了错误的方式;不过,我对 javascript 很陌生。我的问题是如何在这里正确使用这个javasript函数?

最佳答案

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

鉴于此代码片段:

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}, '\"', '\\\"'}

关于java - jsp变量作为javascript函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27496052/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com