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>

截图:

相关文章

JS原生Ajax操作(XMLHttpRequest) GET请求 POST请求 兼容性问题 利用iframe模拟ajax 实现表单提交的返回...
AJAX 每日更新前端基础,如果觉得不错,点个star吧 &#128515; https://github.com/WindrunnerMax/E...
踩坑Axios提交form表单几种格式 前后端分离的开发前后端, 前端使用的vue,后端的安全模块使用的SpringSe...
很早就听闻ajax的名声,但是却一直不知道怎么用,今天自己捣鼓了一下,竟然会用了,哈哈哈哈。 为了防止...
需要在服务器上进行哈 jquery的ajax方法: // jquery请求 $.ajax({ url: &quot;./server/slider.js...
Ajax函数封装ajax.js // Get / Post // 参数 get post // 是否异步 // 如何处理响应数据 // URL // var...