Writing in the front

  • Watch your friends write articlesAJAXWhen the framework defines, andPromise.axiosPut it all together
  • My personal feeling is still a little biased
  • Here is a reading note from my school days
  • I hope that through this article friends canAJAXIt’s clearly defined
  • The main content of the blog is readingAjax BasicsTake notes

Time determines who you meet in your life, your heart determines who you want in your life, and your actions determine who stays ———— walden


The Web of

Berners-lee invented a subset of the Standard Generalized Markup Language (SGML) called HyperText Markup Language (HTML)

Created a simple Protocol called HyperText Transfer Protocol (HTTP),

He also invented the first Web browser, WorldWideWeb.

Web development routines:

Initial Web pages were static, and to make the Web dynamic, CGI(Common Gateway Interfase) was introduced to create programs on the server side using CGI, and CGI scripts can be written in a variety of languages.

Improvements to CGI come with applets, which allow developers to write small applications that can be embedded in Web pages and run applets in the Java Virtual Machine (JVM) of a browser

Later Netscape created a dynamic scripting language, eventually named JavaScript, designed to make applets easier for developers less familiar with Java and the Web, and Microsoft launched VBScript

A year after Java appeared, Sun introduced servlets — Java code that ran on an application server instead of a client-side browser like Apple’s — but the Servlet design interface was inconvenient and needed to be printed as a stream.

In order to separate presentation from business logic, JSP(JavaScript Pages) appeared,Microsoft also launched ASP. To design the page

Microsoft and Sun are not alone in trying to find a solution to the dynamic Web page problem. In the summer of 1996,FutureWave released a product called FutureSplash Animator. The product began as a Java-based animation player and was soon acquired by Macromedia, which renamed the product Flash.

Flash: Use Flash to publish highly interactive applications.

When Microsoft and Netscape released version 4 of their respective browsers,Web developers had a new option: Dynamic HTML (DHTML). DHTML is not a W3C standard.

The DHTML revolution: Dynamic HTML(DHTML) combined with HTML Cascading Style Sheets (CSS),JavaScript,DOM.

Microsoft knew something about interactive applications and was never satisfied with the limitations of the standard request/response pattern, so they came up with remote scripting, but there was no good solution to the synchronous page refresh problem.

Ajax is more of a technique than a specific technology, and JavaScript is a major component of it.

The ajax-related term is the XMLHttpRequest object (XHR), which has been around since Internet Explorer 5 (released in the spring of 1999) as an Active X control. What’s new, however, is browser support. Originally,XHR objects were only supported in IE (thus limiting their use)

But since Mozilla 1.0 and Safari 1.2, support for XHR objects has become common. This seldom-used object and the basic concepts associated with it even appear in the W3C standard: the DOM Level 3 Load and Save Specification. Especially as apps like Google Maps. Google Suggest, Gmail, Flickr, Netflix, and A9 become more accessible,XHR has become the de facto standard.

Who invented Ajax?

The term was first coined in February 2005 by Jesse James Garrett of Adaptive Path. In his article Ajax:A New Approach to Web Applications,Garrett discusses how to bridge the boundary between fat client (or desktop) Applications and thin client (or Web) Applications.

Of course, the technology really took off when Google Maps and Google Suggest were released by Google LABS, and there have been many articles written about it.

But it was Garrett who came up with the name first, otherwise we’d be shivering with a lot of words: Asynchronous, XMLHttpRequest, javasjavascript. CSS, DOM, and so on.

Although Ajax was originally thought of as an acronym for Asynchronous JavaScript + XML, the term has been expanded to include technologies that allow browsers to communicate with servers without refreshing the current page

So how do you define itAJAX: that is,AJAXIs based onThe XMLHttprequest object (XHR)To eliminate the distinction between fat client (desktop) and thin client (Web) applications. throughAsynchronous communication, which allows the browser to communicate with the server without refreshing the current page.

Use the XMLHTTPrequest object

Before you can use the XMLHttpRequest object to send a request and process the response, you must first write JavaScript to create an XMLHttpRequest object.

Since XMLHttpRequest is not a W3C standard, it can be created in a variety of ways. Internet Explorer implements XMLHttpRequest as an ActiveXObject, and other browsers implement it as a native Javascript object.

var xmlHttp
function createXMLHttpRequest(){
	if(window.ActiveXObject){               / / IE browser
		xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
	}else if(window.XMLHttpRequest){   // Other browsers
	   xmlHttp = newXMLHttprequest(); }}Copy the code

Methods and Properties

The method attributes describe
void abort() Stop the current request
String getAllresponseHeadders() Returns all response headers of the HTTP request as key-value pairs as a string
String getResponseheader(“”) Returns a string for the specified header field
void open(string method,string url,boolean asynch,string username,string password) Creates a call to the server that initializes the request’s purely scripted method, with the third parameter indicating whether the call is asynchronous (true) or synchronous (false), the default asynchronous
void send(content) Make a request to the server, return immediately if declared asynchronous, or wait for a response to be received. The optional arguments can be an instance of a DOM object, an input stream, or a string. The content passed into this method is sent as part of the request
void setRequestHeader(string header,string value) Sets the specified header to the supplied value, which must be called open() before setting any header
attribute describe
onreaddystatechange This event handler is triggered with each state change, usually calling event handlers
readystate Request status, 0(uninitialized), 1(loading), 2(loaded), 3(interactive), 4(done)
responseText Returns the server’s response, represented as a string
responseXML The response returned to the server, represented as XML, can be parsed into a DOM object
status HTTP status code of the server
statusText The server status code corresponds to the cause phrase

Interactive instance

<input type = "text" id = "email" name ="email" onblur = "validateEmail()">
<script type = "text/Javascript">
var xmlHttp;
var email  = document.getElementById("email");
var url = "validata? emali = "+escape(email.value);
// Get method data is sent as part of the URl, address data? Separated. Data is displayed in key-value pairs separated by &.
if(window.ActiveXObject){               / / IE browser
		xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
	}else if(window.XMLHttpRequest){   // Other browsers
	   xmlHttp = new XMLHttprequest();
	}
xmlHttp.open("GET",url);
xmlHttp.onreadystatechange = callback;
xmlHttp.send(null);
function callback(){
	if(xmlHttp.readyState == 4) {if(xmlHttp.status ==200) {//do something interesting here}}}}</script>
Copy the code

How do I send a simple request

Basic steps for sending a request using the XMLHttprequest object:

  1. Get an instance reference to the XMLHttpRequest object, and you can create new instances or access existing instance variables.
  2. Sets the object’s onReadyStatechange property to a pointer to the event function.
  3. Specify the requested properties, the open() method
  4. Sends the request to the server, using the send() method, or null if no data is sent as part of the request body;
<! DOCTYPE html PUBLIC"- / / / / W3C DTD XHTML 1.0 Transitional / / EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>simple XMLHttpRequest</title>
<script type="text/Javascript">
var xmlHttp;
function createXMlHttprequest(){
	if(window.ActiveXObject){
		xmlHttp = new ActiveObject("Microsoft.XMLHttp"); 
		}
	else if(window.XMLHttpRequest){
		xmlHttp = newXMLHttpRequest(); }}function srartRequest(){
	createXMLHttprequest();
	xmlHttp.onreadystatechange = handleStateChange;
	xmlHttp.open("GET"."simpleResponse.xml".true);
	xmlHttp.send(null);
	}
function handleStateChange(){
	if(xmlHttp.readyState ==4) {if(xmlHttp.status == 200){
			alert("The servlet replied with:"+xmlHttp.responseYext); }}}</script>
</head>
<body>
<form action="#">
   <input type="button" value="Start Basic Asynchronous Request" onclick="startRequest()" />
</form>
</body>
</html>
Copy the code

Communicating with the server

Handling the server response: The XMLHttpRequest object provides the responseText to provide the response as a string, and the responseXML provides the response as an XML object.

Parse the response into a plain text file.

document.getElementBiId("idName").innerHTML = xmlHttp.responseText;
// Returns the contents of the response as a string, written to IDName.
Copy the code

Parse the response into an XML file:

To make the server respond to the data in XML format, you need the Content_Type to start with text/ XML or, when plain text, text/piain

Attribute methods used to process DOM elements of XML documents

Property method name describe
childNodes Returns an array of all the children of the document element
firstChild Returns the first child of the current element
lastChild Returns the last child of the current element
nextsibling Returns the element immediately following the current element
nodeValue Returns the read/write attribute of the specified element
parentNode Returns the parent node of the element
previousSibling Returns the element immediately before the current element
getElementById(document) Gets an element in a document that has specified unique attributes
hasChildNodes() Returns data for the child element of the current element with the specified tag name
getAttirbut(name) Returns the attribute value of the element, specified by name
var XMLDoc= xmlHttp.responseXML;
// The response is returned in XML format.
Copy the code

Send request parameters: Post puts parameters in the request body to send, get apends parameters to the URL to send. When using the POST method, you need to send the string when calling the send() method of the XMLHttpRequest object.

function doRequestUsingGET(){
	createXMLHttpRequest();
	var queryString = "Request an address?";
	queryString = queryString + createQueryString() +"&timeStamp="+new Date().getTime();
	xmlHttp.onreadystatechange  = handleStateChange;
	xmlHttp.open("GET"."queryString".true);
	xmlHttp.send(null);
}
function doRequestUsingPOST(){
	carterXMLHttpRequest();// Get the XMLHttp object.
	var url = "Request an address? timeStamp="+new Date().getTime();
	var queryString = createQueryString();// Gets the parameter string
	xmlHttp.open("post",url,true);
	xmlHttp.onreadystatechange  = handleStateChange;// Trigger the check state method.
	xmlHttp.setRequestHeader("Content-type"."application/x-www-form-urlencoded;");// Make sure the server knows that there are request parameters in the request body.xmlHttp.send(quweyString); The send() method is called to pass the query string as an argument. }Copy the code

Why append the timestamp to the target URl: Sometimes the browser caches the results of multiple XMLHttpRequest requests to the same URl, and if the response to each request is different, it gives good results. Appending the current timestamp to the end of the YR ensures that the URl is unique.

Request parameters are sent as XML

Sending the request parameters to the server as part of the request body in AN XML format is similar to sending the query string as part of the request body in a POST request, except that the XML string is sent by the SEND method of the XMLHttpRequest object.

Backslash before slash in closing tag: XML = XML + “</ PEST >”; The SGML specification provides a trick to recognize closing tags in script elements, but not other content, using backslashes to avoid parsing strings into tags, which should be used according to strict XHTML standards.

In Java code, XML parameters are obtained through the Request object, converted to a character stream, byte stream, converted to a DOM object through the DocumentBuilderFactory object method, and then parsed through the NodeList object to get the data.

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {
		doGet(request, response);
		String xml = readXMLFromRequestBody(request);
		Document xmlDoc  = null;

			xmlDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
					.parse(new ByteArrayInputStream(xml.getBytes()));	
		}catch(ParserConfigurationException e) {
			e.printStackTrace();
		}catch(SAXException e) {
			e.printStackTrace();
		}
		NodeList selectedPetTypes = xmlDoc.getElementsByTagName("type");
		String type  =null;
		String responseText = "Selectsd Pets";
		for(int i =0; i< selectedPetTypes.getLength(); i++) { type = selectedPetTypes.item(i).getFirstChild().getNodeValue(); responseText = responseText+""+type;
		}
		response.setContentType("text/xml");
		response.getWriter().print(responseText);
		System.out.println(responseText);
	}
	private String readXMLFromRequestBody(HttpServletRequest request) {
		StringBuffer xml = new StringBuffer();// instantiate a character cache object;
		String line = null;
		try {
			BufferedReader reader = request.getReader();// Request the character cache input stream, reading files from the character input stream, one line at a time.
			while((line =reader.readLine())! =null) {// Loop through a line of textxml.append(line); }}catch( Exception e) {
			e.printStackTrace();
		}
		return xml.toString();
	}
Copy the code

Implement basic Ajax techniques

Complete local validation

function validate(){
		createXMLHttpRequest();
		var date = document.getElementById("birthDate");
		var url = "ValidationServlet? birthDate=" + escape(date.value);
		xmlHttp.open("GET",url,true);
		xmlHttp.onreadystatechange = callback;
		xmlHttp.send(null);
		}
	function callback(){
		if(xmlHttp.readyState ==4) {if(xmlHttp.status == 200) {var mes = xmlHttp.responseXML.getElementsByTagName("message") [0].firstChild.data;
				var val = xmlHttp.responseXML.getElementsByTagName("passed") [0].firstChild.data; setMessage(mes,val); }}}function setMessage(message,isvalid){
		var messageArea = document.getElementById("dateMessage");
		var fontColor = "red";
		if(isvalid == "true"){
			fontColor = "green";
			}
		messageArea.innerHTML = "<font color = "+fontColor+">"+message+"</font>";
		}
Copy the code
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		boolean passed  = validateDate(request.getParameter("birthDate"));
		response.setContentType("text/xml; charset=UTF-8");
		response.setHeader("Cache-Control"."no-cache");
		String message = "You have entered an invalid date";
		if(passed){
			message  ="You have entered an invalid date";
		}
		out.println("<response>");
		out.println("<passed>"+Boolean.toString(passed)+"</passed>");
		out.println("<message>"+message+"</message>");
		out.println("</response>");
		out.close();
	}
	private boolean validateDate(String date) {// Determines that the string conforms to the specified date format
		boolean isValid=true;
		if(date! =null) {
			SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/YYYY");
			try {
				formatter.parse(date); // Parse the text of the string to generate Date,
			}catch(ParseException e) {
				e.printStackTrace();
				isValid=false; }}else {
				isValid=false;
			}
		return isValid;
	}
Copy the code
  • Gets the string format of the current time.
  • Read response header
  • When the server responds to a HEAD request, it simply sends the response header ignoring the response content.
function handleStateChange(){
	if(xmlHttp.readyState == 4) {if(requestType =="allResponseHeaders"){
			getAllRequestHeaders();
			}else if(requestType =="lastModified"){
				getLastModified();
				}else if(requestType =="isResourceAvailable"){ getIsResourceAvailable(); }}}function getAllRequestHeaders(){
	alert(xmlHttp.getAllResponseHeaders());
	}
function getLastModified(){
	alert("Last Modified:"+xmlHttp.getResponseHeader("Last-Modified"));
	}
function getIsResourceAvailable(){
	if(xmlHttp.status ==200){
		alert("Successful^_^");
		}else if(xmlHttp.status == 404){
			alert("Resource is unavailable");
		}else{
			alert("Unexpected response status :"+xmlHttp.status);
			}
Copy the code

Ajax has many application scenarios in development, such as the ones below

  • Dynamically load list boxes
  • Create automatic refresh page:
  • Create tooltip:
  • Dynamically update Web pages

JQuery implements Ajax:

The jQuery Ajax method enables HTTP GET or HTTP POST requests for text, HTML, XML, JSON, and data from remote servers, while loading these external data into selected elements of the web page.

Ajax () method: An underlying implementation of jQuery, the $.ajax() method returns the XMLHttpReuqst object it creates. Most do not need to manipulate the object, except to terminate manually in special cases. There is only one argument: the argument is the key/value object, $.ajax(options). This parameter is optional.

$.ajax({
		url:'/ExampleServlet'.type:'post'.dataType:'json'.success:function(data){alert('success! '); alert(data); },error:function(){alert('Internal error');}
		});
Copy the code
$.ajax({
       async:false;
       type:'post';
       url:"example.jsp".data:"name=Jfn&location=boss"
		}).success(function(msg){alert("Data Saved:"+msg)
		}).error(function(xmlHttpRequest,statusText,errorThrown){
		alert("You form submission failed.\n\n"
				+"XMLHttpRequest:"
				+JSON.stringify(xmlHttpRequest)
				+",\nStatusText:"+statusText
				+",\nErroeThrown:"+errorThrown);
		});
Copy the code
  • The load() method loads data from the server and puts the returned data into the selected element:
  • Url: a mandatory parameter that specifies the URL to load
  • Data: Optional, specifying the set of query string key/value pairs to be sent with the request.
  • Callback: Optional callback function that requests successful completion.
  • Get (), POST (): Used to request data from the server via HTTP GET or POST requests,
  • GetJSON () : Loads JSON data through an HTTP GET request and attempts to convert it to the corresponding JavaScript object.

Ajax operations implemented by the Promise object

function ajax(URL) {
    return new Promise(function (resolve, reject) {
        var req = new XMLHttpRequest(); 
        req.open('GET', URL, true);
        req.onload = function () {
        if (req.status === 200) { 
                resolve(req.responseText);
            } else {
                reject(new Error(req.statusText)); }}; req.onerror =function () {
            reject(new Error(req.statusText));
        };
        req.send(); 
    });
}
var URL = "/try/ajax/testpromise.php"; 
ajax(URL).then(function onFulfilled(value){
    document.write('Contents:' + value); 
}).catch(function onRejected(error){
    document.write('Error:' + error); 
});
Copy the code

About AJAX and friends share here