"Dark Horse Programmer _ ultra-comprehensive javaweb video tutorial vedio\javaweb video tutorial _day23_ajax"
\javaweb Video Tutorial _day23_ajax\day23ajax_avi\14. Package ajax build gadget. avi; have introduced;
Personal understanding: is to encapsulate the XMLHttpRequest of the request method, evolved into our common Ajax;
===== the original request method:
Ajax sends asynchronous requests (four-step operation)1. First step (get XMLHttpRequest)*Ajax actually only needs to learn an object: XMLHttpRequest, if mastered it, mastered the ajax!!! *get XMLHttpRequest> Most browsers support: var xmlHttp =NewXMLHttpRequest (); > Ie6.0:var xmlHttp =NewActiveXObject ("Msxml2.xmlhttp"); > IE5.5 with earlier versions of Ie:var xmlHttp =NewActiveXObject ("Microsoft.XMLHTTP"); *Write the function createxmlhttprequest () {that creates the XMLHttpRequest objectTry { return NewXMLHttpRequest (); } Catch(e) {Try { return NewActiveXObject ("Msxml2.xmlhttp"); } Catch(e) {Try { return NewActiveXObject ("Microsoft.XMLHTTP"); } Catch(e) {alert ("Dude, what kind of browser are you using?" "); Throwe; } } } }2. Step two (open a connection to the server)*Xmlhttp.open (): Used to open a connection to the server, it requires three parameters:>Request method: Can be get or post> URL of the request: Specify server-side resources, for example;/day23_1/Aservlet>whether the request is asynchronous: If true means sending an asynchronous request, otherwise the request is synchronized! * Xmlhttp.open ("GET", "/day23_1/aservlet",true);3. Step three (send request)* Xmlhttp.send (NULL): If not given may cause some browsers to fail to send! >parameter: Is the request body content! If it is a GET request, NULL must be given. 4. Fourth step ()*registering listeners on an event of the XMLHTTP object: onReadyStateChange*There are 5 states of the XMLHTTP object:>0 Status: Just created, not yet called the Open () method; >1 Status: Request Start: The open () method is called, but the Send () method has not been called>2 Status: The Send () method has been called;>3 Status: The server has started responding, but does not indicate that the response is over! >4 Status: Server Response end! (usually we only care about this state!!!) )*get the status of the XMLHTTP object:> var state = xmlhttp.readystate;//it could be 0, 1, 2, 3, 4 .*Get status code for server response> var status = Xmlhttp.status;//For example, 200, 404,*get the contents of the server Response 1> var content = xmlhttp.responsetext;//gets the contents of the text format of the response of the server> var content = xmlhttp.responsexml;//get the contents of the response XML response of the server, it is the Document Object! Xmlhttp.onreadystatechange= function () {//This method is called in all 5 states of the XMLHTTP if(Xmlhttp.readystate = = 4 && xmlhttp.status = = 200) {//Double judgment: Judging whether it is a 4 state, and whether it is a//get the response content of the servervar text =Xmlhttp.responsetext; } };====================================================================================Second Example: Send a POST request (usually with a POST request if you need to send a request with parameters)* Open:xmlHttp.open ("POST" ....);* Add one step: Set content-type request Header:> Xmlhttp.setrequestheader ("Content-type", "application/x-www-form-urlencoded");* Send:xmlHttp.send ("username=zhangsan&password=123");//Specify the request body when sending a request
= = teacher-Encapsulated JS---ajaxutils.js
//Create a Request objectfunctioncreatexmlhttprequest () {Try { return NewXMLHttpRequest ();//Most browsers}Catch(e) {Try { returnActviexobject ("Msxml2.xmlhttp");//IE6.0}Catch(e) {Try { returnActviexobject ("Microsoft.XMLHTTP");//IE5.5 and earlier versions}Catch(e) {alert ("Dude, what browser are you using?" "); Throwe; } } }}/** Option Object has the following properties*/ /*Request Method*/method,/*the requested URL*/URL,/*is asynchronous*/Asyn,/*Request Body*/params,/*callback Method*/Callback,/*what type of server response data to convert to*/typefunctionAjax (option) {/** 1. Get XMLHTTP*/ varXmlHttp =createxmlhttprequest (); /** 2. Open the connection*/ if(!option.method) {//default is GET requestOption.method = "GET"; } if(Option.asyn = = undefined) {//default is asynchronous processingOption.asyn =true; } xmlhttp.open (Option.method, Option.url, Option.asyn); /** 3. Determine if it is a post*/ if("POST" = =Option.method) {Xmlhttp.setrequestheader ("Content-type", "application/x-www-form-urlencoded"); } /** 4. Send Request*/xmlhttp.send (Option.params); /** 5. Register for monitoring*/Xmlhttp.onreadystatechange=function() { if(Xmlhttp.readystate = = 4 && xmlhttp.status = = 200) {//Double judgment vardata; //get the response data for the server and convert it! if(!option.type) {//If the type is not assigned, the default is textdata =Xmlhttp.responsetext; } Else if(Option.type = = "xml") {Data=Xmlhttp.responsexml; } Else if(Option.type = = "Text") {Data=Xmlhttp.responsetext; } Else if(Option.type = = "JSON") { varText =Xmlhttp.responsetext; Data= eval ("(" + text + ")"); } //Call callback Methodoption.callback (data); } };};
Call it in the JSP:
<%@ page language= "Java"Import= "java.util.*" pageencoding= "UTF-8"%><%@ taglib prefix= "C" uri= "Http://java.sun.com/jsp/jstl/core"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >window.onload=function () {var btn= document.getElementById ("btn"); Btn.onclick=function () {/*1. Ajax*/Ajax ({URL:"<c:url value= '/aservlet '/>", type:"JSON", Callback:function (data) {document.getElementById ("H3"). InnerHTML = Data.name + "," + Data.age + "," +Data.sex; } } ); };};</script> ====== and now the standard usage:
$(function(){ $(' #send '). Click (function() {$.ajax ({type:"GET", URL:"Test.json", data: {username:$ ("#username"). Val (), content:$ ("#content"). Val ()}, DataType:"JSON", Success:function(data) {$ (' #resText '). empty ();//empty everything inside the restext. varhtml = ' '; $.each (data,function(Commentindex, comment) {HTML+ = ' <div class= "comment" >] + ': ] + ' </p></div> '; }); $(' #resText '). HTML (HTML); } }); });});
= = = Personal Understanding: In fact, it is called a method, the method is filled with parameters (parameters have general type and object type, method type)
The ins and outs of Ajax-if the encapsulated--ajax sends an asynchronous request (four-step operation)