使用 ajax 将集合填充到 UI 上

发布于 2024-10-30 19:45:46 字数 1320 浏览 1 评论 0原文

我正在使用 JSP、Servlet 和 Ajax 以及 Smack API 构建一个聊天应用程序。一旦用户连接到 Gtalk,他的好友列表就会显示在 UI 上。我能够将好友列表放到控制台上,但将其填充到 JSP 上会出现问题。

在我的 servlet 中,我使用以下方式获取好友列表:

  Roster roster = connection.getRoster();
    Collection<RosterEntry> entries = roster.getEntries();
    for(RosterEntry r:entries)
    {
        String user = r.getUser();
        pw.println(user);
    }

在我的 jsp 页面中,我希望在页面加载时填充好友列表:

$(document).ready(function() {
    var xmlhttp;
    if(window.XMLHttpRequest)
    {
    xmlhttp=new XMLHttpRequest();
    }
    else
    {
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
    if(xmlhttp.readyState==4)
    {
        if(xmlhttp.status == 200) 
            {

               document.getElementById(buddies).innerHTML=xmlhttp.responseText;
            }

    }
    }
    xmlhttp.open("POST","LoginIMServlet",true);
    xmlhttp.send(null);
        }
)
<table>
</tr>
  <tr>
    <td>
    <form name=ListForm>
    <select id="buddies" name="buddies" size=40 multiple onclick="window.open("ChatWindow.jsp",width=500,height=350,resizable=yes")>
    </select>
     </form> 
    </td>
  </tr>
</table>

我无法填充多重选择器框。我该如何解决这个问题?

I am building a chat application using JSP, Servlets and Ajax with Smack API. Once the user connects to Gtalk his buddies list should be displayed onto the UI. I am able to get the buddies list onto console but populating it on the JSP is giving problems.

In my servlet I get the buddy list using:

  Roster roster = connection.getRoster();
    Collection<RosterEntry> entries = roster.getEntries();
    for(RosterEntry r:entries)
    {
        String user = r.getUser();
        pw.println(user);
    }

In my jsp page I want the buddy list to be populated on page load:

$(document).ready(function() {
    var xmlhttp;
    if(window.XMLHttpRequest)
    {
    xmlhttp=new XMLHttpRequest();
    }
    else
    {
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
    if(xmlhttp.readyState==4)
    {
        if(xmlhttp.status == 200) 
            {

               document.getElementById(buddies).innerHTML=xmlhttp.responseText;
            }

    }
    }
    xmlhttp.open("POST","LoginIMServlet",true);
    xmlhttp.send(null);
        }
)
<table>
</tr>
  <tr>
    <td>
    <form name=ListForm>
    <select id="buddies" name="buddies" size=40 multiple onclick="window.open("ChatWindow.jsp",width=500,height=350,resizable=yes")>
    </select>
     </form> 
    </td>
  </tr>
</table>

I am not able to populate the multi selector box. How can I solve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

远昼 2024-11-06 19:45:46

如果您想在页面加载期间执行服务器端操作,则不一定需要 JS/Ajax。您可以让 JSP 来完成这项工作。这样就节省了一次HTTP请求的成本。

让 servlet 的 doGet() 方法将其存储在请求范围中并转发到 JSP。

Roster roster = connection.getRoster();
request.setAttribute("rosterEntries", roster.getEntries());
request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);

让 JSP 利用 JSTL 对其进行迭代并打印 元素。

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
...
<select multiple>
    <c:forEach items="${rosterEntries}" var="rosterEntry">
        <option>${fn:escapeXml(rosterEntry.user)}</option>
    </c:forEach>
</select>

fn:escapeXml() 不是强制性的,但它只是防止潜在的 XSS 攻击漏洞)

现在调用 servlet 的 URL,而不是 JSP 的 URL。 JSP 将在“页面加载时”填充它。


与具体问题无关,如果您使用 jQuery,那么您不应该自己创建 XMLHttpRequest 对象。这完全没有道理。只需使用 $.ajax()$.get() 等函数即可。例如,请查看此问题

如果您确实想用 jQuery 解决这个问题,那么最好是让 servlet 以 JSON 形式返回数据,并使用 $.getJSON() 来检索它。请在 doGet() 方法中执行以下操作:

Roster roster = connection.getRoster();
String rosterEntriesJson = new Gson().toJson(roster.getEntries());
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(rosterEntriesJson);

(Gson 位于此处Google GSON,只需下载 JAR 并将其放入 /WEB-INF/lib 中)

将此 servlet 映射到 /buddies 上并执行以下操作JSP/jQuery 中的以下内容:

<script>
    $(document).ready(function() {
        $.getJSON('buddies', function(rosterEntriesJson) {
            var $buddies = $('#buddies');
            $.each(rosterEntriesJson, function(index, rosterEntry) {
                $('<option>').text(rosterEntry.user).appendTo($buddies);
            });
        });
    });
</script>
...
<select id="buddies" multiple></select>

If you want to do server-side stuff during page load, you don't necessarily need JS/Ajax for this. You can just let JSP do the job. This saves the cost of one more HTTP request.

Let the servlet's doGet() method store it in request scope and forward to JSP.

Roster roster = connection.getRoster();
request.setAttribute("rosterEntries", roster.getEntries());
request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);

Let the JSP utilize JSTL <c:forEach> to iterate over it and print the <option> elements.

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
...
<select multiple>
    <c:forEach items="${rosterEntries}" var="rosterEntry">
        <option>${fn:escapeXml(rosterEntry.user)}</option>
    </c:forEach>
</select>

(the fn:escapeXml() is not mandatory, but it just prevents you from potential XSS attack holes)

Now call the URL of servlet instead of the JSP one. JSP will populate it "on page load".


Unrelated to the concrete problem, if you're using jQuery, then you should not create XMLHttpRequest objects yourself. This makes no utter sense. Just use $.ajax(), $.get(), etc functions. For examples, check this question.

If you really want to solve this with jQuery, then best is to let the servlet return the data as JSON and use $.getJSON() to retrieve it. Do the following in the doGet() method instead:

Roster roster = connection.getRoster();
String rosterEntriesJson = new Gson().toJson(roster.getEntries());
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(rosterEntriesJson);

(Gson is here Google GSON, just download and drop JAR in /WEB-INF/lib)

Map this servlet on /buddies and do the following in JSP/jQuery:

<script>
    $(document).ready(function() {
        $.getJSON('buddies', function(rosterEntriesJson) {
            var $buddies = $('#buddies');
            $.each(rosterEntriesJson, function(index, rosterEntry) {
                $('<option>').text(rosterEntry.user).appendTo($buddies);
            });
        });
    });
</script>
...
<select id="buddies" multiple></select>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文