在 AJAX 中处理 servlet 输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1900711/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Handling servlet output in AJAX
提问by sansknwoledge
My problem: I am sending a request to a servlet from an AJAX function in a JSP.
我的问题:我从 JSP 中的 AJAX 函数向 servlet 发送请求。
The servlet processes the data and returns a ArrayList.
servlet 处理数据并返回一个ArrayList.
My question is how to handle the ArrayListinside AJAX, and display it as a table in same JSP.
我的问题是如何处理ArrayList内部的 AJAX,并在同一个 JSP 中将其显示为表格。
The code is
代码是
function ajaxFunction ( ) {
// var url= codeid.options[codeid.selectedIndex].text;
url="mstParts?caseNo=9&cdid=QCYST0020E1";
// alert(cid);
var httpRequest;
if (window.XMLHttpRequest) {
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
if (httpRequest == null){ alert('null');}
alert(url);
httpRequest.open("GET", url, true );
httpRequest.onreadystatechange = function() { alertContents(httpRequest); };
//httpRequest.setRequestHeader('Content-Type', 'text/plain');
httpRequest.send(null);
alert('t1');
}
function alertContents(httpRequest) {
if (httpRequest.readyState == 4) {
var cType =httpRequest.getResponseHeader("Content-Type");
//document.write(httpRequest.toString());
// alert(cType);
// var xmlDoc=httpRequest.responseText;
//document.write(xmlDoc.toString());
// if (xmlDoc == null) {alert('null returned');}
if (!httpRequest.status == 200) {
alert('Request error. Http code: ' + httpRequest.status);
}
else
{
var profileXML = eval(<%=request.getAttribute("data")%>);
if ( profileXML != null){ alert('null'); }//else { alert(profileXML(0)); }
// httpRequest.getAttribute("data");
}
}
}
回答by BalusC
var profileXML = eval(<%=request.getAttribute("data")%>);
var profileXML = eval(<%=request.getAttribute("data")%>);
Firstly, I would recommend you to learn about the wall between JavaScript and JSP. JS runs entirely at the client sideand JSP/Java runs entirely at the server side. They certainly doesn't run in sync as you seem to think. To learn more, read this blog article.
首先,我建议您了解一下 JavaScript 和 JSP 之间的墙。JS 完全运行在客户端,而 JSP/Java 完全运行在服务器端。它们当然不会像您想象的那样同步运行。要了解更多信息,请阅读此博客文章。
function ajaxFunction ( )
function ajaxFunction ( )
Secondly, I would recommend you to use an existing, robust, thoroughly-developed, well-maintained JavaScript library with Ajaxical capabilities such as jQueryinstead of reinventing the AJAX wheel and fighting/struggling/worrying with browser specific issues/troubles/behaviors/pains. I would also recommend to use JSONas data transfer format between Java Servlet at server and JavaScript at client. In the Java side you can use the great Gsonlibrary for this.
其次,我建议您使用具有 Ajaxical 功能的现有的、健壮的、开发完善的、维护良好的 JavaScript 库,例如jQuery,而不是重新发明 AJAX 轮子和与浏览器特定问题/麻烦/行为/痛苦作斗争/挣扎/担心. 我还建议使用JSON作为服务器端 Java Servlet 和客户端 JavaScript 之间的数据传输格式。在 Java 方面,您可以为此使用出色的Gson库。
Here's a kickoff example with all of the mentioned techniques. Let's start with a Servlet and a JavaBean:
这是一个包含所有提到的技术的启动示例。让我们从一个 Servlet 和一个 JavaBean 开始:
public class JsonServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Data> list = dataDAO.list();
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(new Gson().toJson(list));
}
}
public class Data {
private Long id;
private String name;
private Integer value;
// Add/generate getters/setters.
}
The JsonServlet(you may name it whatever you want, this is just a basic example) should be mapped in web.xmlon a known url-pattern, let's use /jsonin this example. The class Datajust represents one row of your HTML table (and the database table).
的JsonServlet(你可以命名为任何你想要的,这只是一个简单的例子)应该被映射web.xml在一个已知的url-pattern,让我们用/json这个例子。该类Data仅表示 HTML 表(和数据库表)的一行。
Now, here's how you can load a table with help of jQuery.getJSON:
现在,您可以通过以下方式在jQuery.getJSON 的帮助下加载表格:
$.getJSON("http://example.com/json", function(list) {
var table = $('#tableid');
$.each(list, function(index, data) {
$('<tr>').appendTo(table)
.append($('<td>').text(data.id))
.append($('<td>').text(data.name))
.append($('<td>').text(data.value));
});
});
The tableidof course denotes the idof the <table>element in question.
该tableid过程的表示id所述的<table>有问题的元素。
That should be it. After all it's fairly simple, believe me. Good luck.
应该是这样。毕竟这相当简单,相信我。祝你好运。

