34 Ajax

1.簡介

image.png

image.png

image.png

image.png

image.png
image.png

image.png

image.png

image.png

image.png

//服務(wù)器端代碼,用于響應(yīng)返回ajax的請求數(shù)據(jù)

//ContentServlet.java
package com.imooc.ajax;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ContentServlet
 */
@WebServlet("/content")
public class ContentServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ContentServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().println("<b>I'm server content</b>");
        //注意:返回給Ajax的數(shù)據(jù),不需要進行頁面跳轉(zhuǎn),通常采用json數(shù)據(jù)回傳
    }

}

前端顯示代碼

//index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <input id="btnLoad" type="button" value="加載">
    <div id="divContent"></div> <!-- 從服務(wù)器獲取的數(shù)據(jù)寫入這個div -->
    <script type="text/javascript">
        document.getElementById("btnLoad").onclick = function(){
            //1.創(chuàng)建XmlHttpRequest對象
            var xmlhttp;
            if(window.XMLHttpRequest){
                xmlhttp = new XMLHttpRequest();
            }else{
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            console.log(xmlhttp);
            //2.發(fā)送Ajax請求
            xmlhttp.open("GET","/Ajax/content",true);//發(fā)送到服務(wù)器地址,采用異步
            xmlhttp.send();
            //3.處理服務(wù)器響應(yīng)
            xmlhttp.onreadystatechange = function(){
                if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
                    var t = xmlhttp.responseText;
                    document.getElementById("divContent").innerHTML = t;//js中往標(biāo)簽中寫入文本,也可用Jquery
                    //
                }
            }
        }
    </script>
</body>
</html>

在前端點擊"加載"按鈕,得到服務(wù)器回傳的Ajax數(shù)據(jù)

2.Ajax 用json傳遞數(shù)據(jù)

//news.java
package com.imooc.ajax;

public class News {
    private String title;
    private String date;
    private String source;
    private String content;
    public News(String title, String date, String source, String content) {
        super();
        this.title = title;
        this.date = date;
        this.source = source;
        this.content = content;
    }
    public News() {
        
    }
    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.java
package com.imooc.ajax;

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 newsList = new ArrayList();
        newsList.add(new News("TIBOBE:全球編程語言排行榜5月","2018-5-1","TIOBE","..."));
        newsList.add(new News("TIBOBE:全球編程語言排行榜6月","2018-5-1","TIOBE","..."));
        newsList.add(new News("TIBOBE:全球編程語言排行榜7月","2018-5-1","TIOBE","..."));
        newsList.add(new News("TIBOBE:全球編程語言排行榜8月","2018-5-1","TIOBE","..."));
        String json = JSON.toJSONString(newsList);
        System.out.println(json);
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().println(json);
    }

}
//news.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <div id="container"></div>
    <script type="text/javascript">
        //1.創(chuàng)建XMLHttpRequest對象
        var xmlhttp;
        if(window.XMLHttpRequest){
            xmlhttp = new XMLHttpRequest();
        }else{
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        //2.發(fā)送Ajax請求
        xmlhttp.open("GET","/Ajax/news_list",true);
        xmlhttp.send();
        //3.處理服務(wù)器響應(yīng)
        xmlhttp.onreadystatechange = function(){
            if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
                var text = xmlhttp.responseText;
                console.log(text);
                //這里的JSON是JS中提供的對象,而非fastjson提供
                var json = JSON.parse(text);//將字符串轉(zhuǎn)換成json
                console.log(json);
                var html = "";
                for(var i=0;i<json.length;i++){
                    var news = json[i];
                    html = html + "<h1>" + news.title + "</h1>";
                    html = html + "<h2>" + news.date + "&nbsp" + news.source + "</h2>";
                    html = html + "<hr/>";
                }
                document.getElementById("container").innerHTML = html;
            }
        }
    </script>
</body>
</html>

3.同步和異步的區(qū)別

同步狀態(tài):代碼進入等待狀態(tài),響應(yīng)不返回,程序不會繼續(xù)向下執(zhí)行,就是前面代碼沒執(zhí)行完后面的代碼就會一直等待
異步狀態(tài):程序不會處于阻塞狀態(tài),程序依舊向下執(zhí)行,數(shù)據(jù)返回時,是通過觸發(fā)onreadystatechange事件進行數(shù)據(jù)的獲取和處理
通常Ajax設(shè)置為異步狀態(tài)

使用了同步,xmlhttp.onereadystatechange=function(){...},該事件失效..(將function()代碼取出來放在send()后面就行了)
同步狀態(tài):代碼進入等待狀態(tài),數(shù)據(jù)不返回,程序不會繼續(xù)向下執(zhí)行
異步狀態(tài):Ajax不會處于程序的阻塞狀態(tài),程序依舊向下執(zhí)行,數(shù)據(jù)返回時,是通過觸發(fā)onreadystatechang事件進行數(shù)據(jù)的獲取和處理
通常Ajax設(shè)置為異步狀態(tài)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容