Ajax
1. 全域重繪和區域重繪
全域重繪和區域重繪圖解
全域重繪:整個瀏覽器被新的資料覆寫,但由于在網路中要傳輸大量的資料,瀏覽器需要加載,渲染頁面,往往給用戶的感受不是很好,
區域重繪:在瀏覽器的內部,發起請求,獲取資料,改變頁面中的部分內容,其余的頁面無需加載和渲染,網路中資料傳輸量少,給用戶的感受好,
ajax就是用來作區域重繪的,區域重繪使用的核心物件是異步物件(XMLHttpRequest)
這個異步物件是存在瀏覽器記憶體中的,使用JavaScript語法創建和使用XMLHttpRequest物件,
2. 什么是AJAX
ajax:Asynchronous JavaScript and XML (異步的JavaScript 和 XML),
- Asynchronous:異步的
- JavaScript:javascript腳本,在瀏覽器中執行
- and:和
- XML:一種資料格式
ajax是一種作區域重繪的新方法,不是一種語言,ajax包含的技術主要有JavaScript、dom、css、xml等,
其中核心是JavaScript和xml,
-
JavaScript:負責創建異步物件,發送請求,更新頁面的dom物件,ajax請求需要服務器端的資料,
-
xml:網路中傳輸的資料格式,
<資料> <資料1> 寶馬1 </資料1> <資料2> 寶馬2 </資料2> <資料3> 寶馬3 </資料3> </資料>但由于它資料較長、冗余又比較啰嗦,在傳輸程序花的時間和空間都不小,逐漸被json所替代了,
3. ajax中使用XMLHttpRequest物件
-
創建異步物件
var xmlHttp = new XMLHttpRequest(); -
給異步物件系結事件
onreadystatechange,當異步物件發起請求,獲取了資料都會觸發這個事件,這個事件需要指定一個函式,在函式中處理狀態的變化,xmlHttp.onreadystatechange = function(){ if (xmlHttp.readyState == 4 && xmlHttp.status == 200){ // 可以處理服務器端的資料,更新當前頁面 var data = xmlHttp.responseText; document.getElementById("name").value=data; } }異步物件的屬性
readystate表示異步物件請求的狀態變化0:創建異步物件時,new XMLHttpRequest();
1:初始異步請求物件,xmlHttp.open( 請求方式,請求地址,true )
2:發送請求,xmlHttp.send()
3:異步物件接收應答資料 從服務端回傳資料,XMLHttpRequest 內部處理, (一般不用,是原始資料)
4: 異步請求物件已經將資料決議完畢, 此時才可以讀取資料,
異步物件的屬性status屬性,表示網路請求的狀況的(200、404、500…),需要是當status==200時,表示網路請求是成功的,
-
初始異步請求物件
使用異步的方法open()
格式:xmlHttp.open(請求方式get|post, "服務器端的訪問地址", 同步|異步請求(默認是true,即異步請求));
例如:xmlHttp.open("get", "loginServlet?name=zs&pwd=123", true); -
使用異步物件發送請求
xmlHttp.send()
獲取服務器端回傳的資料,使用異步物件的屬性responseText:xmlHttp.responseText
回呼:當請求狀態變化時,異步物件會自動呼叫onreadystatechange事件對應的函式,
例子:根據用戶傳入的省份id到資料庫中去查詢對應的省份名稱
- 資料庫表:

-
index.jsp:接收用戶輸入的資料并交給服務器,然后獲取服務器查詢的結果并展示,
<html> <head> <title>$Title$</title> <script type="text/javascript"> function search() { var xmlHttp = new XMLHttpRequest(); xmlHttp.onreadystatechange = function () { if (xmlHttp.readyState == 4 && xmlHttp.status == 200){ document.getElementById("proname").value = xmlHttp.responseText; } } var proid = document.getElementById("proid").value; xmlHttp.open("get", "/myWeb/queryProvince?proid="+proid, true); xmlHttp.send(); } </script> </head> <body> <p>ajax根據省份id獲取名稱</p> <table border="3"> <tr> <td>省份編號:</td> <td> <input type="text" id="proid"> <input type="button" value="搜索" onclick="search()"> </td> </tr> <tr> <td>省份名稱:</td> <td><input type="text" id="proname" readonly></td> </tr> </table> </body> </html> -
queryProvinceServlet:
public class queryProvinceServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String proid = request.getParameter("proid"); String name = "默認是無資料"; if (proid != null && !"".equals(proid.trim())){ ProvinceDao dao = new ProvinceDao(); try { name = dao.queryProvinceNameById(Integer.valueOf(proid)); } catch (SQLException throwables) { throwables.printStackTrace(); } } // 使用HttpServletResponse輸出資料 response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println(name); out.flush(); out.close(); } } -
provinceDao:進行資料庫操作
public class ProvinceDao { // 根據id獲取名稱 public String queryProvinceNameById(Integer proviceId) throws SQLException { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; String sql = ""; String url = "jdbc:mysql://localhost:3306/springdb?serverTimezone=UTC"; String username = "root"; String password = "549436"; String name = ""; // 加載驅動 try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(url, username, password); sql = "select name from province where id=?"; ps = conn.prepareStatement(sql); ps.setInt(1, proviceId); rs = ps.executeQuery(); while(rs.next()){ name = rs.getString("name"); } } catch (Exception e) { e.printStackTrace(); }finally { try { if (rs != null){ rs.close(); } if (ps != null){ ps.close(); } if (conn != null){ conn.close(); } }catch (Exception e){ e.printStackTrace(); } } return name; } } -
運行結果:


4. 引入json
json詳細介紹(這個里面用到的json工具庫是json-lib)
json分類:
- json物件,JSONObject,
- json陣列,JSONArray,
使用json原因:
- json格式好理解
- json格式在多種語言中,比較容易處理
- json格式資料占用空間小,在網路中傳輸快,用戶體驗好
處理json的工具庫:gson(google)、fastjson(阿里)、jackson、json-lib
下面我們要使用jackson工具處理json
不過在使用前我們還需要匯入三個jar包:

例子:使用jackson把Java物件轉為json格式字串(學習使用jackson)
-
物體類Province:
public class Province { private Integer id; private String name; private String jiancheng; private String shenghui; public Province() { } public Province(Integer id, String name, String jiancheng, String shenghui) { this.id = id; this.name = name; this.jiancheng = jiancheng; this.shenghui = shenghui; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getJiancheng() { return jiancheng; } public void setJiancheng(String jiancheng) { this.jiancheng = jiancheng; } public String getShenghui() { return shenghui; } public void setShenghui(String shenghui) { this.shenghui = shenghui; } } -
Test.java:用來測驗
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.moyan.entity.Province; public class Test { public static void main(String[] args) throws JsonProcessingException { Province p = new Province(1, "河北", "冀", "石家莊"); // 使用jackson把p轉為json ObjectMapper om = new ObjectMapper(); // writeValueAsString:把引數的Java物件轉為json格式的字串 String json = om.writeValueAsString(p); System.out.println("轉換的json == " + json); } } 輸出:轉換的json == {"id":1,"name":"河北","jiancheng":"冀","shenghui":"石家莊"}
5. 完整的使用json作為資料交換的格式的例子
輸入省份編號,從資料庫中查詢出該省份編號對應的省份名稱、省份簡稱、省會名稱,服務端將這些資料以JSON字串形式回傳,前端從得到的json中取出資料并展示,
資料庫表:

各檔案:
-
myajax.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>使用json格式資料</title> <script type="text/javascript"> function doSearch() { var xmlHttp = new XMLHttpRequest(); xmlHttp.onreadystatechange = function () { if (xmlHttp.readyState == 4 && xmlHttp.status == 200){ var data = xmlHttp.responseText; var res = eval("("+data+")"); // eval是執行括號中代碼,把json字串轉為json物件 document.getElementById("proname").value = res.name; document.getElementById("projiancheng").value = res.jiancheng; document.getElementById("proshenghui").value = res.shenghui; } } var proid = document.getElementById("proid").value; xmlHttp.open("get", "/myWeb/queryJson?proId="+proid, true); xmlHttp.send(); } </script> </head> <body> <p>ajax請求使用json格式的資料</p> <table> <tr> <td>省份編號:</td> <td> <input type="text" id="proid"> <input type="button" value="搜索" onclick="doSearch()"> </td> </tr> <tr> <td>省份名稱:</td> <td><input type="text" id="proname" readonly></td> </tr> <tr> <td>省份簡稱:</td> <td><input type="text" id="projiancheng" readonly></td> </tr> <tr> <td>省會名稱:</td> <td><input type="text" id="proshenghui" readonly></td> </tr> </table> </body> </html>
-
Province.java
public class Province { private Integer id; private String name; private String jiancheng; private String shenghui; public Province() { } public Province(Integer id, String name, String jiancheng, String shenghui) { this.id = id; this.name = name; this.jiancheng = jiancheng; this.shenghui = shenghui; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getJiancheng() { return jiancheng; } public void setJiancheng(String jiancheng) { this.jiancheng = jiancheng; } public String getShenghui() { return shenghui; } public void setShenghui(String shenghui) { this.shenghui = shenghui; } } -
QueryJsonServlet.java
public class QueryJsonServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String proId = request.getParameter("proId"); Province province = null; if (proId != null && !"".equals(proId.trim())){ ProvinceDao dao = new ProvinceDao(); province = dao.queryProvinceById(Integer.valueOf(proId)); } ObjectMapper om = new ObjectMapper(); String msg = om.writeValueAsString(province); response.setContentType("application/json;charset=utf-8"); PrintWriter out = response.getWriter(); out.println(msg); out.flush(); out.close(); } } -
ProvinceDao.java
public class ProvinceDao { public Province queryProvinceById(Integer proId){ Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; String sql = ""; String url = "jdbc:mysql://localhost:3306/springdb?serverTimezone=UTC"; String username = "root"; String password = "549436"; Province province = null; // 加載驅動 try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(url, username, password); sql = "select * from province where id=?"; ps = conn.prepareStatement(sql); ps.setInt(1, proId); rs = ps.executeQuery(); if(rs.next()){ province = new Province(); province.setId(rs.getInt("id")); province.setJiancheng(rs.getString("jiancheng")); province.setShenghui(rs.getString("shenghui")); province.setName(rs.getString("name")); } } catch (Exception e) { e.printStackTrace(); }finally { try { if (rs != null){ rs.close(); } if (ps != null){ ps.close(); } if (conn != null){ conn.close(); } }catch (Exception e){ e.printStackTrace(); } } return province; } }
運行結果:
? 
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/297598.html
標籤:其他
