使用ajax请求时候:

响应的数据类型由ajax设置的接受数据方式决定:

responseText决定响应的数据类型是文本;

responseXML决定响应的数据类型xml文档。当返回xml文档时候Servlet一定要设置response.setContentType("text/xml;charset=utf-8");根据是否需要缓存,可以设置response.setHeader("Cache-control", "no-cache");



响应数据的格式由Servlet设置ContentType决定:

text/xml   xml

text/html  html

text/plain  文本

application/json  json


下面是jsp--servlet  返回文本、xml文档、json、html的代码:


index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">

	function getXMLHttpRequest() {
		var xmlReq;
		if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlReq = new XMLHttpRequest();
		} else {// code for IE6, IE5
			xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
		}
		return xmlReq;
	}
	
	//返回文本数据测试
	function ajaxText() {
		var oReq = getXMLHttpRequest();
		oReq.open("POST", "TextServlet", true);
		oReq.setRequestHeader("Content-type",
				"application/x-www-form-urlencoded"); //提交表单必须
		oReq.send("name=我是文本&pwd=123");
		oReq.onreadystatechange = function() {
			if (oReq.readyState == 4 && oReq.status == 200) {				
				document.getElementById("myDiv").innerHTML = oReq.responseText; //responseText响应类型是文本
			}
		}
	}
	
	//返回XML文档测试
	function ajaxXML() {
		var oReq = getXMLHttpRequest();
		oReq.open("POST", "HanderServlet", true);
		oReq.setRequestHeader("Content-type",
				"application/x-www-form-urlencoded"); //提交表单必须
		oReq.send("name=我是xml&pwd=111");
		oReq.onreadystatechange = function() {
			if (oReq.readyState == 4 && oReq.status == 200) {
				var xmlObj=oReq.responseXML; //responseXML响应类型是XML文档
				
				var names=xmlObj.documentElement.getElementsByTagName("name");
				var name=names[0].firstChild.nodeValue;
				
				var pwds=xmlObj.documentElement.getElementsByTagName("pwd");
				var pwd=pwds[0].firstChild.nodeValue;
				
				document.getElementById("myDiv").innerHTML=name+","+pwd;
			}
		}
	}

	//返回json文档测试
	function ajaxJSON() {
		var oReq = getXMLHttpRequest();
		oReq.open("POST", "JsonServlet", true);
		oReq.setRequestHeader("Content-type",
				"application/x-www-form-urlencoded"); //提交表单必须
		oReq.send("name=我是json&pwd=111");
		oReq.onreadystatechange = function() {
			if (oReq.readyState == 4 && oReq.status == 200) {
				var resObj=oReq.responseText; //json字符串用文本形式接收			
				var jsonObj1=eval('('+resObj+')');		
				var name1=jsonObj1.name;
				var pwd1=jsonObj1.pwd;				
				document.getElementById("myDiv").innerHTML=name1+","+pwd1;
			}
		}
	}
	
	//返回html
	function ajaxHTML() {
		var oReq = getXMLHttpRequest();
		oReq.open("POST", "HtmlServlet", true);
		oReq.setRequestHeader("Content-type",
				"application/x-www-form-urlencoded"); //提交表单必须
		oReq.send("name=我是html&pwd=111");
		oReq.onreadystatechange = function() {
			if (oReq.readyState == 4 && oReq.status == 200) {
				var resObj=oReq.responseText; //html用文本形式接收			
							
				document.getElementById("myDiv").innerHTML=resObj;
			}
		}
	}
</script>
</head>
<body>

<button οnclick="ajaxText()">ajax请求文本</button>
<button οnclick="ajaxXML()">ajax请求XML文档</button>
<button οnclick="ajaxJSON()">ajax请求json字符串</button>
<button οnclick="ajaxHTML()">ajax请求html</button>
<div id="myDiv"></div>
</body>
</html>



返回文本的Servlet:

package com.ajax.test;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class TextServlet extends HttpServlet {	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("in text");
		request.setCharacterEncoding("utf-8");
		String name=request.getParameter("name");
		String pwd=request.getParameter("pwd");
		System.out.println("name:"+name+",pwd:"+pwd);		
		
		//返回文本数据
		response.setContentType("text/plain;charset=utf-8");
		ServletOutputStream outputStream = response.getOutputStream();
		outputStream.write(name.getBytes("utf-8"));
		outputStream.write(pwd.getBytes("utf-8"));
		outputStream.flush();
		outputStream.close();
	}

}



返回xml文档的Servlet

package com.ajax.test;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class HanderServlet extends HttpServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("in xml");
		request.setCharacterEncoding("utf-8");
		String name=request.getParameter("name");
		String pwd=request.getParameter("pwd");
		System.out.println("name:"+name+",pwd:"+pwd);

		
		//返回xml文档
		response.setContentType("text/xml;charset=utf-8");
		response.setHeader("Cache-control", "no-cache");
		ServletOutputStream outputStream = response.getOutputStream();
		StringBuffer sb=new StringBuffer();
		sb.append("<?xml version='1.0' encoding='utf-8'?>");
		sb.append("<user><name>"+name+"</name><pwd>"+pwd+"</pwd></user>");
		outputStream.write(sb.toString().getBytes("utf-8"));
		outputStream.flush();
		outputStream.close();			
	}

}



返回json字符串的Servlet

package com.ajax.test;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JsonServlet extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("in json");
		request.setCharacterEncoding("utf-8");
		String name=request.getParameter("name");
		String pwd=request.getParameter("pwd");
		System.out.println("{'name':"+name+",'pwd':"+pwd+"}");		
		
		//返回json字符串数据
		response.setContentType("application/json;charset=utf-8");
		ServletOutputStream outputStream = response.getOutputStream();
		String res="{'name':'"+name+"','pwd':'"+pwd+"'}"; //json字符串要写成"{'name':'tom'}"的形式,里面的key和value也要加''写成字符串的形式
		outputStream.write(res.getBytes("utf-8"));	
		outputStream.flush();
		outputStream.close();
	}

}




返回html的Servlet

package com.ajax.test;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HtmlServlet extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("in html");
		request.setCharacterEncoding("utf-8");
		String name=request.getParameter("name");
		String pwd=request.getParameter("pwd");
		System.out.println("name:"+name+",pwd:"+pwd);

		
		//返回html文档
		response.setContentType("text/html;charset=utf-8");
		response.setHeader("Cache-control", "no-cache");
		ServletOutputStream outputStream = response.getOutputStream();
		String res="<font size='2' color='blue'>"+name+pwd+"</font>";
		outputStream.write(res.getBytes("utf-8"));
		outputStream.flush();
		outputStream.close();			
	}

}



GitHub 加速计划 / js / json
41.72 K
6.61 K
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:1 个月前 )
960b763e 3 个月前
8c391e04 6 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐