The Ajax of JavaScript DOM programming Art

Source: Internet
Author: User
Tags http post response code



Ajax is used to summarize the technique of loading page content asynchronously. Previous web apps involve looking at page refreshes, refreshing and reloading the entire page, even if a small part of the page changes. The main advantage of using AJAX to update only a small part of a page is that the request to the page is sent asynchronously to the server. The server does not use the entire page to request it, it will process the request in the background, while the user can continue to browse the page and interact with the page. Your script can load and create page content on demand without interrupting the user's browsing experience. The Ajax,web application can be used to present a feature-rich, interactive, and desktop-like experience.


The core of Ajax technology is the XMLHttpRequest object. This object acts as an intermediary between the script (client) in the browser and the server side. Simple understanding of Ajaxtry-catch error handling statements with two JS scripts:
try {
     // Code that could cause errors
} catch (error) {
     // What to do when an error occurs
} 
First in the HTML current directory to establish a text document input a sentence used to act as a server-side script output the first JS script used to get the XMLHttpRequest object different version of the XMLHTTP object used in different, in order to be compatible with all the servers, the first script is as follows
 
 
function getHTTPObject() {
    if (typeof XMLHttpRequest == "undefined")
        XMLHttpRequest = function () {
            try {return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
                catch (e) {}
            try {return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
                catch (e) {}
            try {return new ActiveXObject("Msxml2.XMLHTTP"); }
                catch (e) {}
            return false;
}
    return new XMLHttpRequest();
}
The above script will eventually return a new XMLHttpRequest or XMLHTTP object, or return False XMLHttpRequest object has many methods, the open method is used to specify the file to be accessed on the server, specify the request type: GET, POST, SEND , the third parameter specifies whether the request is sent and processed asynchronously. Request.open ("Method", "file", true) onReadyStateChange is an event handler that is triggered when the server sends back a response to the XMLHttpRequest object. Request.onreadystatechange = function () {//process response} The browser updates the value of the ReadyState property at different stages: 0 uninitialized 1 loading 2 loading completed 3 Interacting 4 completing the data sent back by the access server With two properties, you can access the data responsexml used to hold the text string as a responsetext to hold content-type=text/xml data, which is actually a DocumentFragment object. This object can be processed using the DOM method. Once you have clarified how to handle the response, you can send the request using the Send method: Request.send (NULL);the use of the Send method parameter in Ajax:In general, parameters that are submitted using Ajax are simple strings that can be written directly to the URL parameter of the open method using the Get method, where the parameter of the Send method is null. For example:
 
var url = "login.jsp?user=XXX&pwd=XXX";
xmlHttpRequest.open("GET",url,true);
xmlHttpRequset.send(null);  


Alternatively, you can use the Send method to pass parameters. Using the Send method to pass parameters using the Post method, you need to set the Content-type header information, analog HTTP POST method to send a form, so that the server will know how to handle the content of the upload. The submission format of the parameter is the same as the URL in the Get method. You must first call the Open method before you can set the header information.


xmlHttpRequest.open("POST","login.jsp",true);
xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
xmlHttpRequest.send("user="+username+"&pwd="+password);





The second script is used to get the content


 
function getNewContent() { var request = getHTTPObject(); if (request) {
        request.open("GET", "example.txt", true);
        request.onreadystatechange = function () { if (request.readyState == 4) { var para = document.createElement("p"); var txt = document.createTextNode(request.responseText);
                para.appendChild(txt);
                document.getElementById(‘new‘).appendChild(para);
            }
        };
        request.send(null);
    } else {
        alert("Sorry, your browser doesn‘t support XMLHttpRequest");
    }
}

addLoadEvent(getNewContent);


Where addloadevent is the load function written by itself


function addLoadEvent(func) { var oldonload = window.onload; if (typeof window.onload != ‘function‘){
        window.onload = func;
    }else {
        window.onload = function () {
            oldonload();
            func();
        }
    }
}





In this way, insert the above two JS scripts into the HTML page that contains the DIV node with the ID new'

<! DOCTYPE html>
<html lang = "en">
<head>
     <meta charset = "UTF-8">
     <title> Ajax </ title>
</ head>
<body>
     <div id = "new"> </ div>

     <script src = "script / addLoadEvent.js"> </ script>
     <script src = "script / getNewContent.js"> </ script>
     <script src = "script / getHTTPObject.js"> </ script>
</ body>
</ html>
It completes a simple Ajax request

Note that: 1. When using Ajax, pay attention to the same-origin policy. Requests sent using the XMLHttpRequest object can only access data whose HTML is in the same domain. 2. After sending the XMLHttpRequest request, the script will continue to execute and will not wait for the response to return. In other words, the script will not wait for the send response, but will continue to execute. For this reason, if other scripts depend on the response of the server, you must write the response code to the function corresponding to the onreadystatechange property, which is asynchronous.
Ajax of JavaScript DOM programming art

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.