ajax發送非同步請求

來源:互聯網
上載者:User

標籤:logs   發送資料   沒有   使用   javascrip   nal   scott   .text   write   

    一、ajax是什麼?

* asynchronous javascript and xml:非同步js和xml
* 它能使用js訪問伺服器,而且是非同步訪問!
* 伺服器給用戶端的響應一般是整個頁面,一個html完整頁面!但在ajax中因為是局部重新整理,那麼伺服器就不用再響應整個頁面!而只是資料!
  > text:純文字
  > xml:大家都熟悉!!!
  > json:它是js提供的資料互動格式,它在ajax中最受歡迎!

二、AJAX發送非同步請求(四步操作)

1. 第一步(得到XMLHttpRequest)
 * ajax其實只需要學習一個對象:XMLHttpRequest,如果掌握了它,就掌握了ajax!!!
 * 得到XMLHttpRequest
    > 大多數瀏覽器都支援:var xmlHttp = new XMLHttpRequest();
    > IE6.0:var xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    > IE5.5以更早版本的IE:var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

2. 第二步(開啟與伺服器的串連)
  * xmlHttp.open():用來開啟與伺服器的串連,它需要三個參數:
  > 請求方式:可以是GET或POST
  > 請求的URL:指定伺服器端資源,例如;/day23_1/AServlet
  > 請求是否為非同步:如果為true表示發送非同步請求,否則同步請求!
  * xmlHttp.open("GET", "/day23_1/AServlet", true);

3. 第三步(發送請求)
  * xmlHttp.send(null):如果不給可能會造成部份瀏覽器無法發送!
  > 參數:就是請求體內容!如果是GET請求,必須給出null。

4. 第四步()
  * 在xmlHttp對象的一個事件上註冊監聽器:onreadystatechange
  * xmlHttp對象一共有5個狀態:
  > 0狀態:剛建立,還沒有調用open()方法;
  > 1狀態:請求開始:調用了open()方法,但還沒有調用send()方法
  > 2狀態:調用完了send()方法了;
  > 3狀態:伺服器已經開始響應,但不表示響應結束了!
  > 4狀態:伺服器響應結束!(通常我們只關心這個狀態!!!)
  * 得到xmlHttp對象的狀態:
  > var state = xmlHttp.readyState;//可能是0、1、2、3、4
  * 得到伺服器響應的狀態代碼
  > var status = xmlHttp.status;//例如為200、404、500
  * 得到伺服器響應的內容1
  > var content = xmlHttp.responseText;//得到伺服器的響應的文字格式設定的內容
  > var content = xmlHttp.responseXML;//得到伺服器的響應的xml響應的內容,它是Document對象了!

三、AJAX第一例,發送get請求

1. 建立伺服器端,用於向用戶端發送資料

package 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 AServlet */@WebServlet("/AServlet")public class AServlet extends HttpServlet {protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println("Hello AJAX!!!");response.getWriter().println("Hello AJAX");}}

 

2.  建立用戶端

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <title>My JSP ‘ajax1.jsp‘ starting page</title>    <meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--><script type="text/javascript">// 建立非同步對象function createXMLHttpRequest() {try {return new XMLHttpRequest();//大多數瀏覽器} catch (e) {try {return ActvieXObject("Msxml2.XMLHTTP");//IE6.0} catch (e) {try {return ActvieXObject("Microsoft.XMLHTTP");//IE5.5及更早版本} catch (e) {alert("不支援該瀏覽器!");throw e;}}}}window.onload = function() {//文檔載入完畢後執行var btn = document.getElementById("btn");btn.onclick = function() {//給按鈕的點擊事件註冊監聽/*ajax四步操作,得到伺服器的響應把響應結果顯示到h1元素中*//*1. 得到非同步對象 */var xmlHttp = createXMLHttpRequest();/*2. 開啟與伺服器的串連  * 指定請求方式  * 指定請求的URL  * 指定是否為非同步請求*/xmlHttp.open("GET", "/Web04/AServlet", true);/*3. 發送請求*/xmlHttp.send(null);//GET請求沒有請求體,但也要給出null,不然FireFox可能會不能發送!/*4. 給非同步對象的onreadystatechange事件註冊監聽器*/xmlHttp.onreadystatechange = function() {//當xmlHttp的狀態發生變化時執行// 雙重判斷:xmlHttp的狀態為4(伺服器響應結束),以及伺服器響應的狀態代碼為200(響應成功)if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {// 擷取伺服器的響應結束var text = xmlHttp.responseText;// 擷取h1元素var h1 = document.getElementById("h1");h1.innerHTML = text;}};};};</script>  </head>    <body><button id="btn">點擊這裡</button><h1 id="h1"></h1>  </body></html>

  

 結果展示:

點擊得到

四、第二例,發送post請求

伺服器端

package 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 AServlet */@WebServlet("/BServlet")public class BServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String name = request.getParameter("username");response.getWriter().println(name);}}

  用戶端的js

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <title>My JSP ‘ajax1.jsp‘ starting page</title>    <meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--><script type="text/javascript">// 建立非同步對象function createXMLHttpRequest() {try {return new XMLHttpRequest();//大多數瀏覽器} catch (e) {try {return ActvieXObject("Msxml2.XMLHTTP");//IE6.0} catch (e) {try {return ActvieXObject("Microsoft.XMLHTTP");//IE5.5及更早版本} catch (e) {alert("不支援該瀏覽器!");throw e;}}}}window.onload = function() {//文檔載入完畢後執行var btn = document.getElementById("btn");btn.onclick = function() {//給按鈕的點擊事件註冊監聽//得到非同步對象var xmlHttp = createXMLHttpRequest();//開啟與伺服器的串連xmlHttp.open("POST", "/Web04/BServlet", true);//佈建要求頭xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");//發送請求xmlHttp.send(‘username=scott&passwd=tiger‘);/*4. 給非同步對象的onreadystatechange事件註冊監聽器*/xmlHttp.onreadystatechange = function() {//當xmlHttp的狀態發生變化時執行// 雙重判斷:xmlHttp的狀態為4(伺服器響應結束),以及伺服器響應的狀態代碼為200(響應成功)if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {// 擷取伺服器的響應結束var text = xmlHttp.responseText;// 擷取h1元素var h1 = document.getElementById("h1");h1.innerHTML = text;}};};};</script>  </head>    <body><button id="btn">點擊這裡</button><h1 id="h1"></h1>  </body></html>

  

五、響應內容為xml的案列

用戶端的編寫

package 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 CServlet */@WebServlet("/CServlet")public class CServlet extends HttpServlet {private static final long serialVersionUID = 1L;protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String xml = "<students>" +"<student number=‘008‘>" +"<name>zhangSan</name>" +"<age>18</age>" + "<sex>male</sex>" +"</student>" +"</students>";response.setContentType("text/xml;charset=utf-8");response.getWriter().print(xml);}}

伺服器端的js編寫

<%@ 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><script type="text/javascript">// 建立非同步對象function createXMLHttpRequest() {try {return new XMLHttpRequest();//大多數瀏覽器} catch (e) {try {return ActvieXObject("Msxml2.XMLHTTP");//IE6.0} catch (e) {try {return ActvieXObject("Microsoft.XMLHTTP");//IE5.5及更早版本} catch (e) {alert("不支援該瀏覽器");throw e;}}}}window.onload = function() {//文檔載入完畢後執行var btn = document.getElementById("btn");btn.onclick = function() {//給按鈕的點擊事件註冊監聽var xmlHttp = createXMLHttpRequest();//開啟與伺服器的串連xmlHttp.open("GET", "/Web04/CServlet", true);//發送請求xmlHttp.send(null);//GET請求沒有請求體,但也要給出null,不然FireFox可能會不能發送!// 給非同步對象的onreadystatechange事件註冊監聽器xmlHttp.onreadystatechange = function() {//當xmlHttp的狀態發生變化時執行// 雙重判斷:xmlHttp的狀態為4(伺服器響應結束),以及伺服器響應的狀態代碼為200(響應成功)if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {// 擷取伺服器的響應結果(xml)var doc = xmlHttp.responseXML;// 查詢文檔下名為student的所有元素,得到數組,再取下標0元素var ele = doc.getElementsByTagName("student")[0];var number = ele.getAttribute("number");//擷取元素名為number的屬性值var name;var age;var sex;// 處理瀏覽器的差異if(window.addEventListener) {name = ele.getElementsByTagName("name")[0].textContent;//其他瀏覽器} else {name = ele.getElementsByTagName("name")[0].text;//IE支援}if(window.addEventListener) {age = ele.getElementsByTagName("age")[0].textContent;//其他瀏覽器} else {age = ele.getElementsByTagName("age")[0].text;//IE支援}if(window.addEventListener) {sex = ele.getElementsByTagName("sex")[0].textContent;//其他瀏覽器} else {sex = ele.getElementsByTagName("sex")[0].text;//IE支援}var text = number + ", " + name + ", " + age + ", " + sex;document.getElementById("h1").innerHTML = text;}};};};</script>  </head>    <body><button id="btn">點擊這裡</button><h1 id="h1"></h1>  </body></html>

  點擊顯示:

 

ajax發送非同步請求

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.