关于javascript 与 JSP 或 Servlet 交互
一般我都是用XMLHttpRequest 异步调用所需要出结果的页面,由该页面返回结果,再显示在需要展现的当前页面.
Example:
1.XMLHttpRequest 请求 result.jsp 页面(result.jsp页面生成我们需要的动态结果).
2.用XMLHttpRequest的responseXML或responseText属性得到result.jsp页面的生成结果.
3.将responseXML或responseText展现在页面上.
这个过程将数据和展现分开;数据由JSP或servlet生成,javascript XMLHttpRequest得到结果,负责展现.
在遇上复杂一些的数据结构时,一般用JSP或servlet生成动态的XML,再由XMLHttpRequest获取这些XML,解析后动态的生成HTML元素,展现出来.
Example:
result.jsp
<%@ page contentType="text/xml; charset=gb2312" %>
<jsp:useBean id="xmlGen" class="sun.test.XMLGen" scope="request"/>
//the javabean visit database for data,and then generate xml string
//finally print it
//and you will see result is xml
response.getWriter().print(xmlGen.generateXML());注意一定要用response.getWriter().print();javascript XMLHttpRequest才能得到XML
out.print()不行.
虽然out.print() 和 response.getWriter().print(),JSP页面看到的结果是一样的..但是只有response.getWriter().print()出来的结果,javascript XMLHttpRequest才能够接收到.
search.html
主要通过javascript XMLHttpRequest 获取 result.jsp 的XML,再动态生成HTML
注意用XMLHttpRequest对象的responseXML.documentElement 来获得XML的root元素,再通过root得到各个所需要的元素.

本文介绍使用JavaScript通过XMLHttpRequest与JSP或Servlet交互的方法,包括请求动态生成的XML并将其解析为HTML的过程。强调了正确使用response.getWriter().print()的重要性。

1384

被折叠的 条评论
为什么被折叠?



