<p>在使用Thymeleaf和AJAX时,我们可以使用Thymeleaf的内联表达式(inline expression)将变量注入到JavaScript代码中。</p>
<p>例如,我们可以将Thymeleaf变量注入到AJAX的URL中,如下所示:</p>
<pre><code>&lt;script th:inline="javascript"&gt;
  $(document).ready(function() {
    var userId = [[${userId}]];
    $.ajax({
      url: '/user/' + userId + '/profile',
      type: 'GET',
      success: function(data) {
        // 处理返回的数据
      }
    });
  });
&lt;/script&gt;</code></pre>
<p>在这个例子中,我们使用`[[${userId}]]`将Thymeleaf变量`userId`注入到了AJAX请求的URL中。这个URL会被渲染成`/user/123/profile`的形式,其中`123`是Thymeleaf变量`userId`的值。</p>
<p>需要注意的是,在使用Thymeleaf内联表达式时,我们需要将`<script>`标签的`th:inline`属性设置为`javascript`,以告诉Thymeleaf这是一段JavaScript代码。</p>
在AJAX URL中使用Thymeleaf变量

原文地址: https://www.cveoy.top/t/topic/mAIc 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录