//这段代码设置响应的数据格式
resp.setContentType("text/xml charset=utf-8");
//设置没有缓存
resp.setHeader("pragma", "no-cache");
resp.setHeader("cache-control", "no-cache");
PrintWriter out = resp.getWriter();
OutputFormat format = new OutputFormat();
XMLWriter xmlWriter = new XMLWriter(out, format.createPrettyPrint());
xmlWriter.write(document);
前端xml.jsp代码如下:
$("#button").click(function()
{
$.post("XMLServlet",
{
"name": $("select").val()
},
function(returnedData, status)
{
var id = $(returnedData).find("id").text();
var name = $(returnedData).find("name").text();
var age = $(returnedData).find("age").text();
var address = $(returnedData).find("address").text();
var html = "
//如果返回的是xml就写成 "text/xml", 如果返回的是json则要写成 "application/json"
resp.setContentType("application/json; charset=utf-8");
//设置没有缓存
resp.setHeader("pragma", "no-cache");
resp.setHeader("cache-control", "no-cache");
PrintWriter out = resp.getWriter();
Gson gson = new Gson();
String result = gson.toJson(list);
// System.out.println(result);
out.println(result);
out.flush();
同样前端的json.jsp代码如下:
$(function()
{
$("#button1").click(function()
{
$.get("GsonServlet", {}, function(returnedData, status)
{
var html = "
id
name
homeAddress
companyAddress
";
for(var i = 0; i < returnedData.length; i++)
{
var id = returnedData[i].id;
var name = returnedData[i].name;
var homeAddress = returnedData[i].address.homeAddress;
var companyAddress = returnedData[i].address.companyAddress;
html += "