Ajax Object Invocation (XML HTTP Request)

Source: Internet
Author: User
Tags add filter object header string version versions access
ajax | request | xml | Object
Author: Jim Ley (Home)
Translator: Sheneyan (子 乌) (Home)
Time: 2006.1.29
English original text: http://jibbering.com/2002/4/httprequest.html
Translation address: http://sheneyan.com/g.php/tech/article/ajax/httprequest.html
Ziwu Note: There are many people who want to read this article, and there are many translated versions. The reason why I want to translate it again is because of the timeliness of this article (see the author's description in the next paragraph) and the elegance of the text. The timeliness of the text, it is actually the version changed again in January 2006, that is, I may be the first person to translate this version: P. The text is elegant, capable, and free to look at the original text. The beauty of English is rarely seen in similar technical articles (perhaps it is rare and strange for me, and it wo n’t be the case when I read more).

This article was written in April 2002. As this object will eventually become more and more popular, I have decided to modify and update this article. The 2002 version can still be read online, as well as the September 2004 and August 2005 editions. You are reading the January 2006 edition.

Internet Explorer on Windows, Safari on Mac OS-X, Mozilla cross-platform, Konqueror on KDE, IceBrowser written in Java, and another cross-platform Opera (including Symbian) all provide a client-side javascript script Method to generate an HTTP request. The humble origin and the weird naming of a few admirers eventually grew into a core technology in some fields, which is called "AJAX" (appreciate the original: From the humble begins as an oddly named object with few admirers, it's blossomed to be the core technology in something called AJAX). [Footnote 1].

对象 This object makes many things more elegant and concise than the original, and introduces something that is equally important in other aspects, such as a HEAD request to see the last modification time of a resource, or just to see if it exists. It makes your scripting choices more flexible, allowing the possibility of POST submission, such as PUT, Delete, and so on, without the need for page changes. These methods are increasingly widely used to create more powerful G-Mail-like web applications that provide snappier user interfaces but use less bandwidth.

Why is it called an "XML" HTTP Request object?
Although this object is called "XML HTTP Request object", it is not limited to using XML. It can request or send any type of document, although processing binary streams is very problematic for JavaScript.

Create object

InternetIn Internet Explorer, you create this object through new ActiveXObject ("Msxml2.XMLHTTP") or new ActiveXObject ("Microsoft.XMLHTTP") (depending on the version of MSXML installed). In Mozilla and Sarafi (and future similar browsers (UA, User Agent) that support this object), you use new XMLHttpRequest (), and IceBrowser uses another method: window.createRequest ().

This means that you need to display different scripts in different browsers (Ziwu Note: Little complaint, I still think this little trouble is much simpler than the compatibility of css ... this is just Personal opinion, maybe after a few months, I am familiar with css, I will not make such complaints ~), code that can be done well on one browser, 80% of the other will be wrong. The following script solves this problem, and if it doesn't support it, the variable xmlhttp will be set to false and the appropriate error message will be allowed. When this object is unavailable, degradation will be reduced and other common http transmission methods will be used. It is important to leave a trail, even in ie, this object is often banned due to slight modification of security settings (usually due to intrusion vulnerabilities in ie). When you really can't implement the function and need to provide low-level support, here are some methods. My suggestion is to provide another workaround page. For example, GMail promised that they will provide a more secure version in the future (Ziwu Note: uh ... this article was written in 2002, at that time gmail did not implement this feature), most likely without JavaScript at all- Total degradation.

var xmlhttp = false;
/ * @ cc_on @ * /
/ * @ if (@_jscript_version> = 5)
// Conditional compilation provided by JScript allows us to cope with older versions of Internet Explorer and the inability to create objects for security reasons
try {
  xmlhttp = new ActiveXObject ("Msxml2.XMLHTTP");
 } catch (e) {
  try {
   xmlhttp = new ActiveXObject ("Microsoft.XMLHTTP");
  } catch (E) {
   xmlhttp = false;
@end @ * /
if (! xmlhttp && typeof XMLHttpRequest! = 'undefined') {
    try {
        xmlhttp = new XMLHttpRequest ();
    } catch (e) {
        xmlhttp = false;
if (! xmlhttp && window.createRequest) {
    try {
        xmlhttp = window.createRequest ();
    } catch (e) {
        xmlhttp = false;
How do I make a request?

Making an HTTP request is very simple. You tell the XML HTTP request object what type of HTTP request you need to make and the URL you want to request. Provide a function to be called when the request completes, and finally, what you need to send in the body of this request (if any).

The script below creates a GET request for "text.txt" for a relative link (relative to the requested page). It provides a callable function that will be called each time the readyState property changes, and when the value of the property becomes 4-meaning that the loading is complete, it uses an alert to display the responseText to the user.

 xmlhttp.open ("GET", "test.txt", true); xmlhttp.onreadystatechange = function () {if (xmlhttp.readyState == 4) {alert (xmlhttp.responseText)}} xmlhttp.send (null)
Make a HEAD request

Xunzi Wu Note: I will translate the header into a header, the HEAD will remain the original, and the resource will be translated into a resource. Personally feel that the header can better reflect the original meaning of the header. ……Ok? Don't you know what the header is? ? This is not a newspaper head. If you understand the definition of the underlying message, you will know that a message, whether it is email or short message, will have at least two parts: the header and the message. The header contains the information of the message, and the message is It is the text. This is a general explanation. If you are still unclear, go to Google ...

For a HEAD request, the server command returns the header of the specified resource without including the resource itself, which means that you can know the Content-Type or Last-Modified of the document without downloading it.

A typical HEAD request might return something like the following:

HTTP / 1.1 200 OK
Server: Microsoft-IIS / 4.0
Cache-Control: max-age = 172800
Expires: Sat, 06 Apr 2002 11:34:01 GMT
Date: Thu, 04 Apr 2002 11:34:01 GMT
Content-Type: text / html
Accept-Ranges: bytes
Last-Modified: Thu, 14 Mar 2002 12:06:30 GMT
ETag: "0a7ccac50cbc11: 1aad"
Content-Length: 52282
提出 To make a HEAD request, you just need to simply replace the first parameter with HEAD, and then you can use getAllResponseHeaders to get the header or getResponseHeader ("Name") to get a separate header.

xmlhttp.open ("HEAD", "/faq/index.html", true); xmlhttp.onreadystatechange = function () {if (xmlhttp.readyState == 4) {alert (xmlhttp.getAllResponseHeaders ())}} xmlhttp. send (null)
Use the HEAD request to find the last modified time of another file.

之一 One of the purposes of the HEAD request is to get the modification time of a certain URL. Extending the previous example, you will get the following code:

 xmlhttp.open ("HEAD", "/faq/index.html", true); xmlhttp.onreadystatechange = function () {if (xmlhttp.readyState == 4) {alert ("File last modified:" + xmlhttp. getResponseHeader ("Last-Modified"))}} xmlhttp.send (null)
Does a URL exist?

Another simple use is to determine whether a URL exists. In HTTP, HEAD and GET requests return a centralized status code. 200 means success, 404 means failure, and some mean something else. See the HTTP status code for a detailed explanation. The xmlhttp object uses the status attribute to tell you this status.

 xmlhttp.open ("HEAD", "/faq/index.html", true); xmlhttp.onreadystatechange = function () {if (xmlhttp.readyState == 4) {if (xmlhttp.status == 200) alert (" URL exists! ") Else if (xmlhttp.status == 404) alert (" URL does not exist! ") Else alert (" Status is "+ xmlhttp.status)}} xmlhttp.send (null)
Call server script without refresh

HTMLIn HTML, forms are a way to call server-side scripts, and they force page refreshes, which are usually not very friendly to users. With Http Request, you can call the script without refreshing the page, and you can use the form when the XML HTTP Request object is not available.

<% a = + (Request.QueryString ('a') + '') b = + (Request.QueryString ('b') + '') if (isNaN (a) | isNaN (b)) {a = ''; b = ''; total = ''} else (total = a + b) acc = Request.ServerVariables ('HTTP_ACCEPT') + '' if (acc.indexOf ('message / x-jl-formresult') ! =-1) {Response.Write (total)} else {%> <script src = "xmlhttp.js" type = "text / javascript"> </ script> <script> function calc () {frm = document. forms [0] url = "add.1? a =" + frm.elements ['a']. value + "& b =" + frm.elements ['b']. valuex
mlhttp.open ("GET", url, true); xmlhttp.onreadystatechange = function () {if (xmlhttp.readyState == 4) {document.forms [0] .elements ['total']. value = xmlhttp.responseText }} xmlhttp.setRequestHeader ('Accept', 'message / x-jl-formresult') xmlhttp.send () return false} </ script> <form action = "add.1" method = "get"> <input type = text name = a value = "<% = a%>"> + <input type = text name = b value = "<% = b%>"> = <input type = text name = total value = "<% = total%> "> <input type = submit value =" Calculate "> </ form> <%}%>
The above example uses asp's jscript as the server language. The HTTP ACCEPT header is used to tell the server what kind of response needs to be sent back-the full page or just the result. This HTTP ACCEPT header is used to tell the server client what mime-types it will accept. Usually it will be something like text / html. Here we tell it that we only accept message / x-jl-formresult, so the server knows that it is a request from our client (or other client that knows message / x-jl-formresult).

Another way to determine the returned content is to infer the type of data you send to the server. You can also simply submit the form to the url of the xmlhttp request to transform it. No matter what you do, it is wise to retain backward compatibility with possible browsers that do not support xmlhttp requests.

Use JSON as the transfer language

Although XML can be used to encode the data you retrieve with this object and access the data through responseXML, XML is still not well supported. Some browsers require that the content type of the resource must be two possible. One of the XML mime-types: text / xml or application / xml can be accepted, and the XML you process may always have well-formed problems. JSON is a good replacement technology, it parses quickly, and, when accessed in a script, is much faster.

I use JSON in my Flight Routeplanner to find flight information, such as London Heathrow. You can easily convert the returned JSON to a script object using the new Function initial function. This object will check the status. If it fails to find a flight, it will return a 404 to the script (it checks the status as the script returns 404 if it fails to find an airport with that iata code).

 xmlhttp.open ("GET", "/ routeplanner / airport.1? LHR", true); xmlhttp.onreadystatechange = function () {if (xmlhttp.readyState == 4) {if (xmlhttp.status! = 404) { var local = new Function ("return" + xmlhttp.responseText) (); alert ("Code-Name \ n" + local [0] .id + '-' + local [0] .name);} else {alert ( "Airport not found");}}} xmlhttp.send (null);
Operate Google's SOAP API using XMLHTTP

Google provides a SOAP interface for its database. In order to make a request, you need to register a key that can be used 1000 times a day. Then you need to parse the returned XML file yourself.

 search = "Word" xmlhttp.open ("POST", "http://api.google.com/search/beta2", true); xmlhttp.onreadystatechange = function () {if (xmlhttp.readyState == 4) { alert (xmlhttp.responseText)}} xmlhttp.setRequestHeader ("Man", "POST http://api.google.com/search/beta2 HTTP / 1.1") xmlhttp.setRequestHeader ("MessageType", "CALL") xmlhttp. setRequestHeader ("Content-Type", "text / xml") xmlhttp.send ("<? xml version = '1.0' encoding = 'UTF-8'?>" + "\ n \ n" + "<SOAP-ENV : Envelope "+ 'xmlns: SOAP-ENV =" http://schemas.xmlsoap.org/soap/envelope/ "' + 'xmlns: xsi =" http://www.w3.org/1999/XMLSchema-instance "'+' xmlns: xsd =" http://www.w3.org/1999/XMLSchema "> '+' <SOAP-ENV: Body> <ns1: doGoogleSearch '+' xmlns: ns1 =" urn: GoogleSearch " '+' SOAP-ENV: encodingStyle = "http://schemas.xmlsoap.org/soap/encoding/"> '+' <key xsi: type = "xsd: string"> GOOGLEKEY </ key> <q '+ 'xsi: type = "xsd: string">' + search + '</ q> <start' + 'xsi: type = "xsd: int"> 0 </ start> <maxResults' +' xsi: type = "xsd : int "> 10 </ maxResults> <filter '+' xsi: type =" xsd: boolean "> true </ filter> <restrict '+' xsi: type =" xsd: stri ng "> </ restrict> <safeSearch '+' xsi: type =" xsd: boolean "> false </ safeSearch> <lr '+' xsi: type =" xsd: string "> </ lr> <ie '+ 'xsi: type = "xsd: string"> latin1 </ ie> <oe' + 'xsi: type = "xsd: string"> latin1 </ oe>' + '</ ns1: doGoogleSearch>' + '</ SOAP-ENV: Body> </ SOAP-ENV: Envelope> ')
Google uses the SOAP interface. Many people think that SOAP has problems that deserve careful consideration. REST may be a better model because it can collaborate with current web frameworks, proxies, caches, and so on. So although we can use XML HTTP Request to communicate with soap, we should try not to use it until we really can't control everything that happens on the server. (Thanks Dan Schmierer for pointing out a bug in my script.)

By default, this object can only call back the same server. In an environment with reduced security requirements (referring to access via file: //), IE can access any domain, and Mozilla can also implement it. If you make a request, Will get the appropriate permissions. (Ziwu Note: I will not translate the following sentence ... What do you mean? "A google thread I can't get to offline!")

Footnote 1: Actually many "AJAX" applications hardly use this XML HTTP REQUEST object, instead they use older, but in most cases more flexible IFRAME to execute remote script methods, but they ("AJAX" applications) You can also use this object, and you should develop the idea that AJAX is an application created using XML HTTP REQUEST.
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.