up:: Ajax简介

这个例子主要是展示在实际中,前后端交互时候,传输的文本常常是JSON的形式!

基本内容:

News.java:

 
    /**
     * JavaBean
     * @author Administrator
     *
     */
    public class News {
    	private String title;
    	private String date;
    	private String source;
    	private String content;
    	private News() {}
 
    	public News(String title, String date, String source, String content) {
    		super();
    		this.title = title;
    		this.date = date;
    		this.source = source;
    		this.content = content;
    	}
    	public String getTitle() {
    		return title;
    	}
    	public void setTitle(String title) {
    		this.title = title;
    	}
    	public String getDate() {
    		return date;
    	}
    	public void setDate(String date) {
    		this.date = date;
    	}
    	public String getSource() {
    		return source;
    	}
    	public void setSource(String source) {
    		this.source = source;
    	}
    	public String getContent() {
    		return content;
    	}
    	public void setContent(String content) {
    		this.content = content;
    	}
 
 
    }
 

NewsListServlet类:

(1)后台处理后的数据向前台传的时候,需要转成JSON;这需要引入fastjson的jar包;

(2)这个Servlet并没有主动重定向至news.html;而是在这儿默默的等待,等待news.html的Ajax的XmlHttpServlet主动去请求访问这个servlet;

(3)这个Servlet通过,response.getWriter().println(newsJsonStr);将数据加入到了响应中去了;嗯就可以这样理解!!!

 
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
 
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
 
    import com.alibaba.fastjson.JSON;
 
    /**
     * Servlet implementation class NewsListServlet
     */
    @WebServlet("/news_list")
    public class NewsListServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
 
        /**
         * @see HttpServlet#HttpServlet()
         */
        public NewsListServlet() {
            super();
            // TODO Auto-generated constructor stub
        }
 
    	/**
    	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
    	 */
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 
    		List<News> list = new ArrayList<News>();
    		list.add(new News("标题1","2021-1-1","TIOBE","内容1"));
    		list.add(new News("标题2","2021-1-2","TIOBE","内容2"));
    		list.add(new News("标题3","2021-1-3","TIOBE","内容3"));
    		// 在Servlet处理后,对外进行字符串序列化的时候,一律将其转化为JSON;通过JSON,可以对数据进行有效的描述;
    		// 然后在前端的html中,再通过JavaScript自带的JSON处理方式,将从这儿发送过去的数据进行解析
    		// 将List转成JSON需要,引入fastjson包
    		String newsJsonStr = JSON.toJSONString(list);
    		System.out.println(newsJsonStr);
    		response.setContentType("text/html;charset=UTF-8"); // json中包含了中文
    		response.getWriter().println(newsJsonStr);
    	}
 
    }
 

news.html:

 
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    	<div id="container"></div>
    	<script>
    		// 1.创建XmlHttpRequest对象
    		var xmlhttp;
    		if(window.XMLHttpRequest){
    			xmlhttp = new XMLHttpRequest();
    		}else{
    			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    		}
    		// 2.发送Ajax请求
    		xmlhttp.open("GET","/ajax/news_list",true);
    		xmlhttp.send();
    		// 3.处理服务器响应
    		xmlhttp.onreadystatechange = function(){
    			if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
    				var t = xmlhttp.responseText;  // 从后台拿过来的数据:这个JSON是个JSON字符串
    				var jsont = JSON.parse(t);  // 需要将JSON字符串转成JSON对象;JavaScript可以认为内置了JSON对象
    				console.log(t);
    				console.log(jsont);
    				var html = "";
    				for(var i = 0;i< jsont.length;i++){
    					var news = jsont[i];
    					html = html+"<h1>"+news.title+"</h1>";
    					html = html + "<h2>"+news.date+" "+news.source+" "+news.content + "</h2>";
    					html = html + "<hr/>";
    				}
    				document.getElementById("container").innerHTML = html;
    			}
    		}
    	</script>
    </body>
    </html>

效果:html中ajax部分,会去请求访问servlet,获取响应中的文本,处理后展示在界面上;

注:

(1)innerHTML是JavaScript中DOM对象的属性;虽然可以利用jQuery中的text(),html()等方法设置元素的属性值;;;;但是jQuery只是在JavaScript基础上的一个“plugin”,而且目前jQuery使用度逐渐下降;

所以千言万语一句话,JavaScript才是王道!!!!!【前端框架天天变,JavaScript是基础!!!】;;;