Ajax:getting started (Chinese)

Source: Internet
Author: User
Tags object header http request object model string version window access
Ajax| Chinese


Start AJAX



Having recently started studyingAJAX (asynchronous JavaScript and XML), it is fortunate that Google has come to this ajax:getting started, published on Devmo . This simple and understandable article translation is as follows, share with you, hope to be helpful to everyone!



This article gives you a basic understanding of Ajax and gives you two examples of easy access.



Directory


    1. What is Ajax?
    2. First step: How to issue an HTTP request
    3. Step Two: Handle the server's response
    4. Step Three: A simple example
    5. Step Fourth:work with XML responses


What is Ajax



Ajax is a new composite term that implies two JavaScript features that have been in existence for many years, but until recently it has been noticed by many web developers as a sensation in Gmail, Google suggest, and Google Maps.



The characteristics of the two JavaScript we are discussing are that you can:


    • Making a request to the server without reloading any pages
    • Parsing XML documents and working with them


Ajax is an abbreviation,a refers to "asynchronous"(asynchronous), it means that you can send an HTTP request to the server, while doing other things, while waiting for the response of the server. JA denotes "JavaScript", andX represents "XML"(extensible Markup Language).



First step: How to issue an HTTP request



To send an HTTP request to the server with JavaScript, you need an instance of the class to provide you with this functionality. This class was originally presented as an ActiveX object in IE, calledXMLHTTP. Then Mozilla, Safari, and some other browsers followed, and there was aXMLHttpRequestclass that supported the original methods and properties of Microsoft's ActiveX objects.



So, in order to be able to create objects of this class across browsers, you need this:


if (window. XMLHttpRequest) {//Mozilla, Safari, ...
    Http_request = new XMLHttpRequest ();
else if (window. ActiveXObject) {//IE
    Http_request = new ActiveXObject ("Microsoft.XMLHTTP");
}
(The code in the example above is a simple version used to build the XMLHTTP instance, as in actual use, see step three of this article)


If the server-side response does not contain an XML Mime-type header (header), some versions of Mozilla browsers may not handle it. So, for security reasons, you can impose the header on the server-side response in a special way, in case it's not atext/xmltype.


http_request = new XMLHttpRequest();
http_request.overrideMimeType('text/xml');


The next step is for you to decide what you are going to do after the server responds to your request. At this stage, you only need to tell the HTTP request object which JavaScript function to use to handle the response. This step is implemented by setting the objectonreadystatechangeproperty to the corresponding JavaScript function name:


http_request.onreadystatechange = nameOfTheFunction;



Note that there are no parentheses following the function name. In addition, the following functions are defined to handle the response:


http_request.onreadystatechange = function(){// Handling the response
};


Next, now that you've declared what you're doing after receiving a response, you need to make a request. You need to invoke the and method of the HTTP request classopen()send():


http_request.open('GET', 'http://www.example.org/some.file', true);
http_request.send(null);
    • open()The first parameter of the method is the way the HTTP request--get, POST, head, or whatever else you want to use, the way your server supports it. The name of the method is capitalized, otherwise some browsers, such as Firefox, may not be able to process the request. You can go to the specs to get more information about how you can use HTTP requests.
    • The second parameter is the URL of the page you are requesting.
    • The third parameter is used to set whether the request is asynchronous. If so, theTRUEJavaScript function continues to execute when the server has not returned a response. This is the meaning of a in Ajax.



send()The parameter of the method can make any data that you want to pass to the server, the data should be a query string in the following format:


name=value&anothername=othervalue&so=on


Step Two: Process the server response



Remember, when you send a request to the server, you emit a name that is designed to handle the response in a JavaScript function.



http_request.onreadystatechange = nameOfTheFunction;



Let's take a look at what this function should do. First, it needs to check the status of the request, and if the status is 4, then it means that all the server responses have been accepted and you can proceed with it.


if (http_request.readyState == 4) {// Everything is ready, phase reflection has been accepted and completed
} else {// not ready
}
readyStateThe list of full values is as follows:
    • 0 (/uninitialized not initialized)
    • 1 (Loading/loading)
    • 2 (Finished loading/loaded)
    • 3 (interactive/interactive)
    • 4 (Complete/complete)
( Source)


The next step is to check the condition code of the HTTP server response. All of the possible code is listed on the web site of the world's online consortium . At present, we are only interested in the200 OKresponse.


if (http_request.status == 200) {// Great!
} else {// Something went wrong with the request, // For example, the response may be 404 (Not Found), not found // or 500, internal server error

}


After you check the status of the request and the HTTP response, you can decide what to do with the data the server sends to you. You have two ways to access this data:


    • http_request.responseTextwill return the server's response as a text string
    • http_request.responseXMLwill return the response as anXMLDocumentobject, you can use JavaScript's Document Object Model (DOM) function to handle


Step Three: A simple example



I'm going to make a simple HTTP request now. Our JavaScript script will request an HTML document that contains atest.htmlpiece of text--"This is a test." "--and then we'll bealert() test.htmlcontent.


<script type="text/javascript" language="javascript">
var http_request = false;

function makeRequest(url) {http_request = false;if (window.XMLHttpRequest) { // Mozilla, Safari,...http_request = new XMLHttpRequest();if (http_request.overrideMimeType) {http_request.overrideMimeType('text/xml');}} else if (window.ActiveXObject) { // IEtry {http_request = new ActiveXObject("Msxml2.XMLHTTP");} catch (e) {try {http_request = new ActiveXObject("Microsoft.XMLHTTP");} catch (e) {}}}if (!http_request) {alert('Giving up :( Cannot create an XMLHTTP instance');return false;}http_request.onreadystatechange = alertContents;http_request.open('GET', url, true);http_request.send(null);
}

function alertContents() {if (http_request.readyState == 4) {if (http_request.status == 200) {alert(http_request.responseText);} else {alert('There was a problem with the request.');}}
}
</script>

<span
style="cursor: pointer; text-decoration: underline"
>
Make a request
</span>


In this example:


    • The user clicks "Make a request" in the browser (make a requests);
    • This invokes themakeRequest()function, with parameterstest.html, the name of an HTML document from the same directory.
    • The request is sent, and then (onreadystatechange) The operation is passed toalertContents();
    • alertContents()Check that the response is received and that the status is OK, and thenalert() test.htmlthe contents of the file.


You can test this example here , and you can see the test file here .



Work with XML responses



In the previous example, after the HTTP response was received, we used the attribute of the Request objectresponseText, which contained thetest.htmlcontents of the file. Now, let's try theresponseXMLproperties.



Let's create a valid XML document right now, and the document will be requested by us later. Documents (Test.xml) include:


<?xml version="1.0" encoding="utf-8" ?>
<root>This is a test. </root>
We just need to replace the request line with the following in the script:
...
>
...
And then inalertContents()In thealert()Row Replace withalert(http_request.responseText);, and, above it, write:
var xmldoc = http_request.responseXML;
var root_node = xmldoc.getElementsByTagName('root').item(0);
alert(root_node.firstChild.data);


In this way, we get theresponseXMLobjects in andXMLDocumentuse the DOM method to access some of the content contained in the XML document. You can browse to it heretest.xml, and the updated script can be obtained here .



You can go to Mozilla's DOM implementation to get more DOM methods.




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.