JavaScript Ajax Programming Applications
- 2021-07-01 06:30:01
- OfStack
1. Ajax (Asynchronous JavaScript + XML) can request additional data like the server without offloading 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: The examples in this section apply to the server side
1. Call the open () method. It accepts three parameters: the type of request to be sent ("get", "post", etc.), the URL of the request, and a Boolean value indicating whether the request is sent asynchronously.
2. To send the request, call the send () method and accept one parameter, which is the body to send the request. null if not required
3. The returned data is automatically populated in the properties of the XHR object.
var xhr = createXHR();
// GET Mode synchronization opens example.txt Documents
// Synchronization: javascript The code will wait for the server to respond before executing
xhr.open("get", "example.txt", false);
xhr.send(null);
// status That represents the response http Status
// 200 Representative ok , 304 Representation cache
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
alert(xhr.responseText); // Returns the text of the response, 123456
} else {
alert("Request was unsuccessful: " + xhr.status);
}
4. example. text file content is string: 123456
4. The previous use of the synchronous way, of course, there will be no problems, so we have to challenge an asynchronous method.
var xhr = createXHR();
// xhr.readyState Indicate a request / The current state of the response, 4 It means that all the response data has been accepted
// In addition, as long as xhr.readyState Has changed the value of, then xhr.onreadystatechange Event triggers the
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 comes with the corresponding header information
1. By default, the following header information is sent along with the XHR request.
① Accept: The type of content that the browser can handle.
② Accept-Charset: The character set that the browser can display.
③ Accept-Encoding: Compression encoding that can be handled by browsers.
④ Accept-Language: The language currently set by the browser.
⑤ Connection: The type of connection between browser and server.
⑥ Cookie: Any Cookie set on the current page.
⑦ Host: The domain where the requested page is located.
8 Referer: URI of the page from which the request was made.
Pet-name ruby User-Agent: The user agent string for the browser.
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 Indicate a request / The current state of the response, 4 It means that all the response data has been accepted
// In addition, as long as xhr.readyState Has changed the value of, then xhr.onreadystatechange Event triggers the
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);
// Must be in the open() After that, call
xhr.setRequestHeader("name", "zhang"); // In example.txt Adj. http You can see the accepted "name" : "zhang"
xhr.send(null);
3. Get the header information of the request and the corresponding information, and call the getResponseHeader () method and the getAllResponseHeaders () method
var xhr = createXHR();
// xhr.readyState Indicate a request / The current state of the response, 4 It means that all the response data has been accepted
// In addition, as long as xhr.readyState Has changed the value of, then xhr.onreadystatechange Event triggers the
xhr.onreadystatechange = function(){
if (xhr.readyState == 4){
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
// Object of the response header Content-Type
var connection = xhr.getResponseHeader("Content-Type");
// alert(connection); // text/plain
// Get all the 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 extend 1 and add 1 parameter to GET request
/**
url : Without request url
name : Request key
value : Request value
return : With a request string url
*/
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");
// Requested url Into: example.txt?name=zhang&age=23
xhr.open("get", url, true);
xhr.send(null);
7. POST Request
1. Case analysis: Next, let's discuss an ajax application that sends requests by post method, that is, user registration, and return prompts according to your registered user name.
2. Implementation steps
1) First of all, there must be a registration page (of course, this is very crude) 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 a user name </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>
</body>
</html>
2) Then, of course, the javascript section
① EventUtil. js, only the part of event monitoring is listed here
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": // Check box
if (!field.checked){
break;
}
/* Perform the default action */
default:
// Does not contain form fields without names
if (field.name.length){
parts.push(encodeURIComponent(field.name) + "=" +
encodeURIComponent(field.value));
}
}
}
return parts.join("&");
}
③ ajax. js is the above createXHR () function, which will not be listed here.
④ ajaxDo. js, the core file, is our operation part, and the name is scribbled.
var form = document.forms[0]; // Get a form
var username = form.elements['username']; // User name
var userLabel = document.querySelector("#userLabel"); // Prompt label
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 is true Prompt for green font when
// When is false When, the prompt is red font
if(text) {
userLabel.style.color = "green";
userLabel.firstChild.data = " Congratulations, the user name 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. Improvements: As you can see, we just serialized the form when we submitted it. The FormData type is defined for this purpose at the XMLHttpRequest 2 level, which automatically serializes the form for us without having to write it ourselves.
We only move part of the code
var xhr = createXHR();
// GET Mode synchronization opens example.txt Documents
// Synchronization: javascript The code will wait for the server to respond before executing
xhr.open("get", "example.txt", false);
xhr.send(null);
// status That represents the response http Status
// 200 Representative ok , 304 Representation cache
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
alert(xhr.responseText); // Returns the text of the response, 123456
} else {
alert("Request was unsuccessful: " + xhr.status);
}
0
8. Other parts (understood, because compatibility is not enough)
1. Timeout settings
var xhr = createXHR();
// GET Mode synchronization opens example.txt Documents
// Synchronization: javascript The code will wait for the server to respond before executing
xhr.open("get", "example.txt", false);
xhr.send(null);
// status That represents the response http Status
// 200 Representative ok , 304 Representation cache
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
alert(xhr.responseText); // Returns the text of the response, 123456
} else {
alert("Request was unsuccessful: " + xhr.status);
}
1
2. The overrideMimeType () method for the type returned by the server
var xhr = createXHR();
// GET Mode synchronization opens example.txt Documents
// Synchronization: javascript The code will wait for the server to respond before executing
xhr.open("get", "example.txt", false);
xhr.send(null);
// status That represents the response http Status
// 200 Representative ok , 304 Representation cache
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
alert(xhr.responseText); // Returns the text of the response, 123456
} else {
alert("Request was unsuccessful: " + xhr.status);
}
2
3. Progress events
1. load event, which is triggered whenever the browser receives information from the server
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, which is triggered periodically during the browser receiving new data
var xhr = createXHR();
// GET Mode synchronization opens example.txt Documents
// Synchronization: javascript The code will wait for the server to respond before executing
xhr.open("get", "example.txt", false);
xhr.send(null);
// status That represents the response http Status
// 200 Representative ok , 304 Representation cache
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
alert(xhr.responseText); // Returns the text of the response, 123456
} else {
alert("Request was unsuccessful: " + xhr.status);
}
4
The above is the whole content of this paper, hoping to help everyone's study.