js實現 AJAX
阿新 • • 發佈:2018-11-28
AJAX:
非同步的技術,可以非同步和伺服器發生資料互動
同步: 需要重新整理資料直接重新整理整個頁面,同步
非同步: 重新整理資料時,使用ajax向伺服器發起請求得到響應之後再區域性重新整理頁面
瀏覽器在向伺服器發請求時需要封裝請求報文[請求首行 請求頭 請求空行 請求體]
XMLHttpRequest:可以通過此物件幫助我們封裝請求報文,還可以通過此物件向伺服器傳送請求
傳送請求時,代表請求報文
響應回來時,又代表響應報文
1、建立XMLHttpRequest物件
2、配置引數[url地址+請求方式+請求引數]
3、傳送請求
4、接收伺服器的響應結果
5、根據結果使用dom區域性修改頁面
XML的缺點:
雖然容易理解,但是傳輸效率差
JSON:
1、js中解析json使用JSON物件 stringify(jsonObj), parse(jsonStr);
2、java中一般是將物件或集合轉為json字串
Gson:[需要匯入jar包]
可以將物件轉為json字串
將json字串轉為java物件
簡單程式碼樣例:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript"> window.onload = function(){ var btn = document.getElementById("btn"); var btn01 = document.getElementById("btn01"); var div = document.getElementById("div"); //點選按鈕傳送ajax請求 btn.onclick = function(){ //1、建立物件 var xhr = new XMLHttpRequest(); //2、設定引數 /* {String} method 請求方式:get/post {String} url 請求地址 {Boolean} optional async 是否非同步 預設true , false同步 {String} optional username {String} optional password */ var method = "GET"; var url = "${pageContext.request.contextPath}/AServlet?username=laowang&age=20"; xhr.open(method, url); //3、傳送請求 xhr.send(); //4、接收伺服器響應資料[js程式碼執行比較快,伺服器的響應此時還沒回來,不能直接獲取資料] //只有當請求碼為4時才代表響應成功並且資料解析成功 //設定狀態碼的改變監聽,每次改變時系統會自動呼叫xhr的onreadystatechange方法 xhr.onreadystatechange = function(){ // alert(xhr.readyState); //只有響應狀態碼為200才代表成功,解析資料顯示到頁面 if(xhr.readyState==4 && xhr.status==200){ //代表響應成功 var text = xhr.responseText; //alert(text); //顯示到頁面中 div.innerHTML += text; }else{ //alert("響應錯誤!!"); } }; }; btn01.onclick = function(){ //1、建立XMLHttpRequest物件[IE5和IE6不支援此物件需要考慮相容性問題] var xhr = new XMLHttpRequest(); //2、設定引數 var method = "POST"; var url = "${pageContext.request.contextPath}/AServlet"; xhr.open(method,url); //3、傳送請求 //ajax傳送請求時,預設是get方式提交,伺服器解析時不知道有請求體不會解析 //如果是post方式提交資料,需要告訴伺服器請求體中有資料需要解析 xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xhr.send("username=laosong&age=20"); //4、設定響應狀態監聽 xhr.onreadystatechange = function(){ if(xhr.status==200&& xhr.readyState==4){ //響應成功,獲取響應資料 //responseText:接收普通文字使用 //responseXML:接收xml格式的文字,此屬性會自動將xml格式的文字封裝為Document物件 div.innerHTML += xhr.responseText; //alert(xhr.responseXML); // var doc = xhr.responseXML; } }; }; }
Servlet層
package com.atguigu.ajax.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class AServlet
*/
public class AServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//response.setContentType("text/html;charset=utf-8");
//如果響應的是xml格式的文字需要設定xml格式
response.setContentType("text/html;charset=utf-8");
//獲取請求引數
String username = request.getParameter("username");
String age = request.getParameter("age");
System.out.println("請求到達AServlet---"+username+"--"+age);
User user = new User(1, "liujinghan", "123456", " [email protected]");
System.out.println("daoda");
//驗證使用者是夠存在
//通過response給ajax響應資料
//response.getWriter().write("恭喜你使用者名稱可用!");
//不可以直接寫物件,將user轉為xml格式傳遞
//String userXml = "<users><user><username>liujinghan</username><age>30</age><email>[email protected]</email></user></users>";
String jsonStr = "{\"username\":\"laowang\",\"age\":20}";
response.getWriter().write(jsonStr);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}