【问题标题】:JS variable, assigned with session attributes, is empty until page reload分配有会话属性的 JS 变量在页面重新加载之前为空
【发布时间】:2021-06-24 11:11:58
【问题描述】:

我有一个在我的 servlet 中设置会话属性的代码:

session.setAttribute("culturesJsonArray", CommonUtils.toJson(foundLanguage.getCultures()));

以及存储这个变量的jsp页面上的js变量

<script>let cultures = ${sessionScope.culturesJsonArray};</script>

在第一页加载一个空数组[],在页面重新加载后我得到一个填充了会话属性值的数组。为什么会发生?

【问题讨论】:

    标签: javascript java jsp session


    【解决方案1】:

    这是因为 AJAX 调用没有刷新 DOM,所以页面上看不到会话属性。我通过发送会话属性来响应 servlet 来解决它:

    PrintWriter out = httpServletResponse.getWriter();
    String page = PagesManager.getProperty("page.languageEditorCultures");
    Map<String, String> attributes = new HashMap<>();
    attributes.put(
    "cultures", CommonUtils.convertListOfObjectsToJson(foundLanguage.getCultures())
    );
    Response response = new Response(page, attributes);
    String jsonResponse = CommonUtils.convertObjectToJson(response);
    out.print(jsonResponse);
    

    并使用 JQuery 的这些属性创建我的 html 元素。

    (响应具有pageNameattributes 字段的自定义类)

    【讨论】:

      猜你喜欢
      • 2014-02-12
      • 2016-05-12
      • 2017-01-15
      • 2014-11-09
      • 2020-04-30
      • 1970-01-01
      • 1970-01-01
      • 2014-03-26
      • 2014-11-25
      相关资源
      最近更新 更多