1. Ajax (Asynchronous JavaScript + XML) can request additional data like the server without uninstalling the page, that is, local refresh technology
2. Create an XHR object
function createXHR () { if (typeof XMLHttpRequest != "undefined") { return new XMLHttpRequest(); } else if (typeof ActiveXObject != "undefined") { // < Ie7 if (typeof arguments.callee.activeXString != "string") { var version = ["MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp"], i, len; for ( i = 0, len = version.length; i < len; i++) { try { new ActiveXObject(version[i]); arguments.callee.activeXString = version[i]; break; } catch (ex) {} } } return new ActiveXObject(arguments.callee.activeXString); } else { throw new Error("No Support For XHR"); } } var xhr = createXHR(); alert(xhr); // [object XMLHttpRequest]3. Usage Note: All examples in this section are applied to the server side
1. Call the open() method. It accepts 3 parameters: the type of request to be sent ("get", "post", etc.), the URL of the request, and the Boolean value indicating whether the request is sent asynchronously.
2. To send a request, call the send() method and accept a parameter, that is, it is to be the subject of the request. null if not required
3. The returned data will be automatically filled into the properties of the XHR object.
var xhr = createXHR(); // Open the example.txt file in GET synchronously // Synchronization: the javascript code will wait for the server to respond and execute xhr.open("get", "example.txt", false); xhr.send(null); // status represents the http status of the response// 200 represents ok, 304 represents the cache if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){ alert(xhr.responseText); // Return the text of the response, 123456 } else { alert("Request was unsuccessful: " + xhr.status); }4.Example.text file content is a string: 123456
4. Of course, there will be no problem with the synchronization method used in the previous process. We have to challenge an asynchronous method.
var xhr = createXHR();// xhr.readyState represents the current status of the request/response, and 4 represents that all the response data has been accepted// In addition, as long as the value of xhr.readyState changes, the xhr.onreadystatechange event will trigger xhr.onreadystatechange = function(){ if (xhr.readyState == 4){ if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){ alert(xhr.responseText); } else { alert("Request was unsuccessful: " + xhr.status); } } }; xhr.open("get", "example.txt", true); xhr.send(null);
5. Each HTTP request and response will have corresponding header information.
1. By default, while sending an XHR request, the following header information will also be sent.
①Accept: The type of content that the browser can handle.
②Accept-Charset: The character set that the browser can display.
③Accept-Encoding: Compressed encoding that the browser can handle.
④Accept-Language: The language currently set by the browser.
⑤Connection: The type of connection between the browser and the server.
⑥Cookies: Any cookies set on the current page.
⑦Host: The domain where the page where the request was issued is located.
⑧Referer: URI of the page that issued the request.
⑨User-Agent: The browser's user agent string.
2. Use the setRequestHeader() method to set custom request header information. Accept two parameters: the name of the header field and the value of the header field
var xhr = createXHR(); // xhr.readyState represents the current status of the request/response, and 4 represents that all the response data has been accepted// In addition, as long as the value of xhr.readyState changes, the xhr.onreadystatechange event will trigger xhr.onreadystatechange = function(){ if (xhr.readyState == 4){ if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){ alert(xhr.responseText); } else { alert("Request was unsuccessful: " + xhr.status); } } }; xhr.open("get", "example.txt", true); // xhr.setRequestHeader("name", "zhang"); // The accepted "name" can be seen in the http of example.txt: "zhang" xhr.send(null);3. Get the request header information and corresponding information, call the getResponseHeader() method getAllResponseHeaders() method
var xhr = createXHR(); // xhr.readyState represents the current status of the request/response, and 4 represents that all the response data has been accepted// In addition, as long as the value of xhr.readyState changes, the xhr.onreadystatechange event will trigger xhr.onreadystatechange = function(){ if (xhr.readyState == 4){ if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){ // Get the Content-Type of the response header var connection = xhr.getResponseHeader("Content-Type"); // alert(connection); // text/plain // Get all response information var all = xhr.getAllResponseHeaders(); alert(all); } else { alert("Request was unsuccessful: " + xhr.status); } } } }; xhr.open("get", "example.txt", true); xhr.send(null);6. GET request. We have discussed the method of GET request before. Now let’s expand it and add some parameters to the GET request.
/** url : url without request name : request key value : request value return : url with request string */ function addURLParam(url, name, value) { url += (url.indexOf("?") == -1 ? "?" : "&"); url += encodeURIComponent(name) + "=" + encodeURIComponent(value); return url; } var xhr = createXHR(); xhr.onreadystatechange = function(){ if (xhr.readyState == 4){ if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){ alert(xhr.responseText); } else { alert("Request was unsuccessful: " + xhr.status); } } } }; var url = "example.txt"; url = addURLParam(url, "name", "zhang"); url = addURLParam(url, "age", "23"); // The requested url becomes: example.txt?name=zhang&age=23 xhr.open("get", url, true); xhr.send(null);7. POST request
1. Case analysis: Next, let’s discuss ajax application that sends requests in the post method, that is, user registration, and the prompt will be returned based on your registered user name.
2. Implementation steps
1) First, there must be a registered page (of course, it is very simple here) ajax.html
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title> Untitled Document</title> <style> </style> </head> <body> <form name="myForm" method="post"> Name: <input type="text" name="username" /><label id="userLabel">Please enter the username</label><br/> Password: <input type="password" name="password" /><br/> <input type="submit" value="Login" /><br/> </form> <script src="EventUtil.js"></script> <script src="serialize.js"></script> <script src="ajax.js"></script> <script src="ajaxDo.js"></script> <script src="ajaxDo.js"></script> </body> </html>
2) Then of course the javascript part
①EventUtil.js, here is just a list of the event listening parts
var EventUtil = { addEvent : function (element, type, handler) { if (element.addEventListener) { element.addEventListener(type, handler, false); } else if (element.attachEvent) { element.attachEvent("on" + type, handler); } } } }②serialize.js: form serialization
function serialize(form){ var parts = [], field = null, i, len, j, optLen, option, optValue; for (i=0, len=form.elements.length; i < len; i++){ field = form.elements[i]; switch(field.type){ case "select-one": case "select-multiple": if (field.name.length){ for (j=0, optLen = field.options.length; j < optLen; j++){ option = field.options[j]; if (option.selected){ optValue = ""; if (option.hasAttribute){ optValue = (option.hasAttribute("value") ? option.value : option.text); } else { optValue = (option.attributes["value"].specified ? option.value : option.text); } parts.push(encodeURIComponent(field.name) + "=" + encodeURIComponent(optValue)); } } } break; case undefined: //field set case "file": //file input case "submit": //submit button case "reset": //Reset button case "button": //Custom button break; case "radio": //Radio button case "checkbox": //Checkbox if (!field.checked){ break; } /* Perform the default operation*/ default: //Discontains form fields without names if (field.name.length){ parts.push(encodeURIComponent(field.name) + "=" + encodeURIComponent(field.value)); } } } return parts.join("&"); }③ajax.js is the createXHR() function above, and it will not be listed here.
④ajaxDo.js, the core file, is the operation part of our name, which is written randomly.
var form = document.forms[0]; // Get form var username = form.elements['username']; // Username var userLabel = document.querySelector("#userLabel"); // Prompt tag EventUtil.addEvent(username, "blur", function() { var xhr = createXHR(); xhr.onreadystatechange = function(){ if (xhr.readyState == 4){ if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){ var text = xhr.responseText; // When true, green font is prompted // When false, red font is prompted if(text) { userLabel.style.color = "green"; userLabel.firstChild.data = "Congratulations, the username is available"; } else { userLabel.style.color = "red"; userLabel.firstChild.data = "Sorry, this user already exists"; } } else { alert("Request was unsuccessful: " + xhr.status); } } } }; // POST request xhr.open("post", "dome.php", true); // Submitted content type xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // Serialize the form xhr.send(serialize(form)); });3. Improvement part: Everyone has seen it. When we submitted the form just now, we serialized the form. The FormData type is defined for this at XMLHttpRequest level 2, which will automatically serialize the form for us and we don't need to write it ourselves.
We only move some of the code
// ...The omitted code here is consistent with the above // POST request xhr.open("post", "dome.php", true); // It only needs to be changed here to replace the previous function xhr.send(new FormData(form));8. Other parts (understand because compatibility is not enough)
1. Timeout setting
xhr.open("get", "example.txt", true); xhr.timeout = 1000; //Set the timeout to 1 second (only for IE8+) xhr.ontimeout = function(){ alert("Request did not return in a second."); }; xhr.send(null);2. overrideMimeType() method, the type returned by the server
var xhr = createXHR(); xhr.open("get", "example.txt", true); xhr.overrideMimeType("text/xml"); // The previous one was text/plain xhr.send(null);3. Progress Events
1.load event, triggered as long as the browser receives the server's information.
var xhr = createXHR(); xhr.onload = function(){ if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){ alert(xhr.responseText); } else { alert("Request was unsuccessful: " + xhr.status); } }; xhr.open("get", "example.txt", true); xhr.send(null);2. Progress event, periodically triggered during the browser receiving new data
var xhr = createXHR(); xhr.onprogress = function(event){ var divStatus = document.getElementById("status"); // Calculate the percentage of data that has been received from the response if (event.lengthComputable){ divStatus.innerHTML = "Received " + event.position + " of " + event.totalSize +" bytes"; } }; xhr.open("get", "altevents.php", true); xhr.send(null);The above is all about this article, I hope it will be helpful to everyone's learning.