Ajax获取响应的纯文本

前端之家收集整理的这篇文章主要介绍了Ajax获取响应的纯文本前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

代码

GetStudentServlet.java

package com.servlet;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GetStudentServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    public GetStudentServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
	protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
		// TODO Auto-generated method stub
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/xml");
		PrintWriter out=response.getWriter();
		out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		out.println("<students>");
		out.println("<student id=\"123\">");
		out.println("<name>张三</name>");
		out.println("</student>");
		out.println("</students>");
	}
	protected void doPost(HttpServletRequest request,IOException {
		// TODO Auto-generated method stub
		doGet(request,response);
	}

}

responseText.html

<!DOCTYPE html>
<html>
<head>
<Meta charset="UTF-8">
<title>使用responText属性获取纯文本</title>
</head>
<body>
  <script type="text/javascript">
    function  getXMLHTTPRequest() {
		var xRequest=null;
		if(window.XMLHttpRequest){
			xRequest=new XMLHttpRequest();
		}
		else if(window.ActiveXObject){
			xRequest=new ActiveXObject("Microsoft.XMLHTTP");
		}
		return xRequest;
	}
    
    function sendRequest(req,url,params,HttpMethod) {
		if(!HttpMethod){
			HttpMethod="POST";
		}
		if(req){
			req.open(HttpMethod,true);
			req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			req.send(params);
		}
	}
    
    //创建与浏览器兼容的XMLHttpRequest对象
    var xmlhttp=getXMLHTTPRequest();
    
    xmlhttp.onreadystatechange=function(){
    	if(xmlhttp.readyState==4){
    		if(xmlhttp.status==200){
    			alert(xmlhttp.responseText);//输出纯文本
    		}
    		else{
    			alert(xmlhttp.status);
    		}
    	}
    }
    
    sendRequest(xmlhttp,"GetStudentServlet",null,"get");
    
  </script>
</body>
</html>

截图:

猜你在找的Ajax相关文章