【问题标题】:How to proceed JSTL tags via javascript如何通过 javascript 处理 JSTL 标签
【发布时间】:2013-04-07 20:49:18
【问题描述】:

我必须在 javascript 响应处理程序函数中处理 JSTL 标记 (fmt:)。例如:

  1. 我需要通过 AJAX 切换语言,所以我需要通过 javascript 更新我的工具面板,并在响应处理程序函数 (javascript) 中继续 fmt:setLocale
  2. 我必须通过 ajax 更新我的选择下拉菜单,并且它们必须翻译适当的本地化,所以我必须在 javascript 中使用 fmt:message

但是,jsp引擎不处理.js文件,我的代码也不行:

document.findElementById("div1").innerHTML = "<fmt:message key="word_from_DB"/>";
document.findElementById("div2").innerHTML = "<fmt:setLocale value="en"/>";

问题:如何从 javascript 中处理这些标签,或者我应该在哪里搜索替代标签?

【问题讨论】:

  • 你能解决这个问题吗?我也需要帮助!
  • @FarazDurrani 幸运的是我几年前就停止使用 JSP 了 :)
  • 大声笑你为什么说幸运?你不喜欢jsp?你现在用什么?
  • @FarazDurrani Redux 或 Angular 2。我在编写 SPA 应用程序时获得了更多乐趣。还有JSP不是过时的技术吗?
  • 我猜是的。但一切顺利。小心。 ty

标签: javascript ajax jsp


【解决方案1】:

您如何准确实现您想要的取决于您的 JSP 和 JS 文件的内容,但这是一种潜在的解决方案:

JS:

function setDivInnerHTML(html1, html2) {
    document.findElementById("div1").innerHTML = html1;
    document.findElementById("div2").innerHTML = html2;
}

JSP:

...
<script>
setDivInnerHTML("<fmt:message key="word_from_DB"/>", "<fmt:setLocale value="en"/>");
</script>
...

编辑基于 cmets:

JSP (URL = "/cities"):

String country = request.getParameter("country");
String locale = request.getParameter("locale");
List<City> cities = getCitiesFromDB(country, locale);
out.println(objectToJSON(cities));

JS(使用 jQuery):

function createOption(val, html) {
    return $("<option></option>").html(html).val(val);
}

function populateCities(cities) {
    var $select = $("#city_select");
    $select.empty();
    for (var i = 0; i < cities.length; i++) {
        var $opt = createOption(cities[i].name, cities[i].name);
        $select.append($opt);
    }
}

function getCities(country, locale) {
    var url = "/cities";
    return $.ajax(url, {
        data: {
            country: country,
            locale: locale
        }
    });
}

// call this to load the initial cities
// and do the same thing when a new country or locale is selected
getCities(country, locale).then(populateCities);

【讨论】:

  • 但我必须从 BD 中提取 word_from_BD。例如,我有三个链接的选择菜单:首先我选择国家,我需要将所有城市setDivInnerHTML("")' 因为,我现在没有关键值
  • 那么你现在如何请求城市?它们以什么格式返回?
  • 我通过 XMLHttpRequest 请求城市,并传递参数“国家”。然后我在服务器上查询数据库并获取该国家所有城市的 ArrayList。然后我通过 JSON 将此 ArrayList 返回到 .js 文件中的句柄函数。
  • 是的,感谢您提供广泛的示例,但我仍然不明白它如何帮助我附加城市选项值由于本地化。 'var $opt = createOption(cities[i].name, urban[i].name)' 如何帮助我将城市[i].name 值更改为三种语言,具体取决于本地化?
  • getCities 将根据国家和地区加载城市。 country 和 locale 在请求中传递。 JSP 将只返回与国家和地区相对应的城市,因为它只根据国家和地区向数据库询问城市。
猜你喜欢
  • 2017-02-18
  • 2015-06-14
  • 2022-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-29
  • 1970-01-01
  • 2013-12-23
相关资源
最近更新 更多