关于返回一个XML格式数据到界面由JQUERY解析
程序员文章站
2022-06-09 08:08:54
...
function aa()
{
var url="http://localhost:8085/Jquery/registservlet";请求的Servlet
$.post(url,null,function(data)
{
var content = "";
alert(data);
$(data).find("rightdiv").find("便捷导航").each(function(index){
content = $(this).find("String").text();
alert(index+"\t"+content);
$('<li><a href="#"></a></li>').html(content).appendTo('#sub1');
});
});
}
<body onload="aa()">
servlet 中------------------------------
response.setContentType("text/xml");//这句是关键写清楚,既然返回是XML 就不要写成HTML
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
ArrayList leadConList = new ArrayList();
leadConList.add("中国");
leadConList.add("美国");
Element rootElt = new Element("rightdiv"); //创建跟节点,名称为student
Element LeadElt = new Element("便捷导航");
Element imgNewsElt = new Element("图片新闻");
Element hotNewsElt = new Element("热点新闻");
for (int i = 0; i < leadConList.size(); i++) {
Element nameElt = new Element("String");
nameElt.addContent((String)leadConList.get(i));
LeadElt.addContent(nameElt);
}
rootElt.addContent(LeadElt);
System.out.print("已经进来");
//rootElt.addContent(imgNewsElt);
//rootElt.addContent(hotNewsElt);
Document doc = new Document(rootElt);
XMLOutputter outXML = new XMLOutputter(); //定义新XML文档
// outXML.setFormat(Format.getCompactFormat().setEncoding("gb2312")); // 默认UTF-8,这里可以设置GBK
String xmlStr = outXML.outputString(doc);
out.print(xmlStr);
{
var url="http://localhost:8085/Jquery/registservlet";请求的Servlet
$.post(url,null,function(data)
{
var content = "";
alert(data);
$(data).find("rightdiv").find("便捷导航").each(function(index){
content = $(this).find("String").text();
alert(index+"\t"+content);
$('<li><a href="#"></a></li>').html(content).appendTo('#sub1');
});
});
}
<body onload="aa()">
servlet 中------------------------------
response.setContentType("text/xml");//这句是关键写清楚,既然返回是XML 就不要写成HTML
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
ArrayList leadConList = new ArrayList();
leadConList.add("中国");
leadConList.add("美国");
Element rootElt = new Element("rightdiv"); //创建跟节点,名称为student
Element LeadElt = new Element("便捷导航");
Element imgNewsElt = new Element("图片新闻");
Element hotNewsElt = new Element("热点新闻");
for (int i = 0; i < leadConList.size(); i++) {
Element nameElt = new Element("String");
nameElt.addContent((String)leadConList.get(i));
LeadElt.addContent(nameElt);
}
rootElt.addContent(LeadElt);
System.out.print("已经进来");
//rootElt.addContent(imgNewsElt);
//rootElt.addContent(hotNewsElt);
Document doc = new Document(rootElt);
XMLOutputter outXML = new XMLOutputter(); //定义新XML文档
// outXML.setFormat(Format.getCompactFormat().setEncoding("gb2312")); // 默认UTF-8,这里可以设置GBK
String xmlStr = outXML.outputString(doc);
out.print(xmlStr);