ajax请求servlet刷新html页面

1、java类

    package testsub;
    public class Sys {
        /**
        * 获取到一条消息
        **/
	public static String getMessage() {
		return "模拟,请求后端,返回一条消息";
	}
    }

2、servlet类

    package testsub;
    import java.io.IOException;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    public class MyServlet extends HttpServlet{
	private static final long serialVersionUID = -7820821330469179359L;
	@Override
	public void init() throws ServletException {
		super.init();
	}
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
                req.getParameter("selecttime");//获取ajax请求参数
		String str=Sys.getMessage;
		resp.getWriter().print(str);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
    }

3、servlet配置

    <servlet>
 	<servlet-name>myservlet</servlet-name>
 	<servlet-class>testsub.MyServlet</servlet-class>
    </servlet>
    <servlet-mapping>
 	<servlet-name>myservlet</servlet-name>
 	<url-pattern>*.do</url-pattern>
    </servlet-mapping>

4、html代码

<html>
<head>
<meta charset="UTF-8">
<title>测试请求后台数据成功否</title>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(function(){
             var selecttime='参数';
	 $.ajax({
			url:'uuu.do',
			type:'POST',//GET 或POST
			async:true,//false是否异步
                            data:{selecttime:selecttime},    
			dataType:'text',//返回的数据格式类型json/xml/html/script/jsonp/text    (返回的值很关键,如果不是text类型,页面可能会被重写)
			success:function(data){
				console.log(data);
				$("#sss").html(data);
			},
			error:function(data){
				console.log(data);//在前端控制台打印请求的状态
			}
		});
})
</script>
</head>
<body>
<h1 id="sss"></h1>
</body>
</html>
posted @ 2017-04-28 11:07  goumingming  阅读(4138)  评论(0编辑  收藏  举报