【问题标题】:Pass Thymleaf variable to Javascript Function将 Thymeleaf 变量传递给 Javascript 函数
【发布时间】:2020-09-02 23:34:12
【问题描述】:

我想将 Thymleaf 变量传递给 javascript 函数。我的百里香叶是这样的

<a class="cat-title"  th:onclick="|fetchProduct('${category.categoryId}','${businessId}')|">
                                    <p th:text="${category.name}"></a>

而我的javascript代码是这样的

   function fetchProduct(businessId,categoryId) {

    var productUrl = '/webstore/business/' + businessId + '/category/' + categoryId + '/products';
    ............
    ............
    }   

但是当我加载页面时出现此错误

引起:org.thymeleaf.exceptions.TemplateProcessingException:仅 允许返回数字或布尔值的变量表达式 上下文中,任何其他数据类型在此上下文中均不受信任 表达式,包括字符串或任何其他可能的对象 呈现为文本文字。

这个错误的原因是什么?

【问题讨论】:

标签: javascript spring-boot thymeleaf


【解决方案1】:

试试这个

<a class="cat-title"  th:onclick="fetchProduct([[${category.categoryId}]], [[${businessId}]]);">
    <p th:text="${category.name}"></a>

【讨论】:

    【解决方案2】:

    我猜原因可能是这个错误https://github.com/thymeleaf/thymeleaf/issues/707 不久前报告的。

    你可以尝试内联 JS 变量:

    <a class="cat-title" 
       th:onclick="'javascript:fetchProduct(\'' + [[${category.categoryId}]] + '\', \'' + [[${businessId}]] + '\');'">
           <p th:text="${category.name}">
    </a>
    

    还有另一种方法也应该可以工作(还没有在编辑器中检查过!)但它看起来更好一些,因为你不需要连接字符串和这么多的 \' :)

    <a class="cat-title" 
        th:dataCatId="${category.categoryId}"
        th:dataBizId="${businessId}" 
        th:onclick="javascript:fetchProduct(this.getAttribute('dataCatId'), this.getAttribute('dataBizId'));">
            <p th:text="${category.name}">
    </a>
    

    【讨论】:

    • “this.getAttribute('dataCatId')”是什么意思?
    • @user3692033 this 在该上下文中指的是您的 HTML 元素 agetAttribute() 方法是您如何获取某些属性的值。 developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute。我相信 Thymeleaf 会生成带有 2 个自定义属性的纯 HTML 并且可以通过 getAttribute() 方法访问它们,因此您不需要内联 JS 内容和连接字符串等。跨度>
    猜你喜欢
    • 2016-08-21
    • 2015-05-02
    • 2017-04-30
    • 2018-12-14
    • 2014-10-31
    • 2018-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多