Ajax Object Invocation (XML HTTP Request)

Source: Internet
Author: User
Tags add filter object header string version versions access
ajax|request|xml| objects
    1. Author: Jim Ley (Homepage)
    2. Translator: Sheneyan (Home)
    3. Time: 2006.1.29
    4. Original English: http://jibbering.com/2002/4/httprequest.html
    5. Address: http://sheneyan.com/g.php/tech/article/ajax/httprequest.html

Sub-note: This article I want to see a lot of people, the translation of a lot of versions, I want to translate again, because of the timeliness of this article (see the next paragraph of the author), as well as the elegance of the text. The timeliness of the text, it is actually January 2006 again changed version, that is, I may be the first translation of this version of the people OH: P. The elegance of the text, has the ability, has the time still to have a look at the original text, that English beauty, in similar technical article count very rare (perhaps I shaojianduoguai, wait me to look too much will not be so ~)

This article was written in April 2002 and I have decided to revise and update this article because it will eventually become more and more popular. The 2002 edition can still be read online, as well as the September 2004 and August 2005 editions. What you are reading is the January 2006 edition.

On Windows Internet Explorer,mac os-x on safari, across platform Mozilla,kde on Konqueror,java write Icebrowser, And another Cross-platform opera (including Symbian) provides a way for client-side JavaScript scripts to generate HTTP requests. The humble origins and the quirky naming of a few advocates eventually grew to be the core technology in some areas, called "AJAX" (see the original: From the humble begins as a oddly named object with few admirers, it ' s Blossomed to is the core technology in something called AJAX). [footnote 1].

This object makes many things more elegant and concise, and introduces something else that is important in other ways, such as the head request to see the last modification time of a resource, or just to see if it exists. It gives you the code (scripting? The choice is more flexible, allowing post submissions such as put, delete, and so on, without the need for page changes. These methods are increasingly being applied to creating Web applications that are more powerful to provide a faster (snappier) user interface, but use less bandwidth, similar to G-mail.

Why is it called an "XML" HTTP Request object?

Although this object is called an "XML HTTP request Object", it is not limited to using XML, it can request or send any type of document, although it is problematic for JavaScript to handle binary streams.

Creating objects

In Internet Explorer, you new ActiveXObject("Msxml2.XMLHTTP") new ActiveXObject("Microsoft.XMLHTTP") create this object by or depending on the version of MSXML that is installed. In Mozilla and Sarafi (and future browsers that support this object like both of them (Ua,user agents), you use new XMLHttpRequest() , and Icebrowser use another method: window.createRequest() .

This means that you need to display different scripts in different browsers (sub-note: A little complain, I still think this little trouble than the compatibility of CSS, more simple .... This is just a personal view, perhaps a few months, I am familiar with the CSS, will not make such a complaint ~), in a browser can do good code, on the other one above 80% will be wrong. The following script solves the problem, and if it does not, the variable XMLHTTP will be set to false and allow the appropriate error message to be lowered when the object is not available (degradtion), using other normal HTTP transmission methods. It is important to have a retreat, even in IE, where this object is often banned because of a slight change in security settings, usually caused by IE's intrusion vulnerabilities. When you are really unable to implement features and need to provide low level support, the bottom is a few methods. My suggestion is to provide another alternative page. Gmail, for example, promises to say that they are in the future (sub-note: er ...). This article was written in 2002, when Gmail did not implement the feature, will provide a more secure version, it is likely that there is no javascript--complete degradation.

var Xmlhttp=false;
/ * @cc_on@*/
/ * @if(@_jscript_version >= 5)
The conditional compilation provided by JScript allows us to cope with older versions of IE and 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) {
if (!xmlhttp && window.createrequest) {
try {
XMLHTTP = Window.createrequest ();
catch (e) {

How do I make a request?

Making an HTTP request is very simple. You tell the XML HTTP request object What types of HTTP requests you need to make and the URLs you want to request. Provide a function to call it when the request is complete, and, finally, what you need to send in the body of the request (if any).

The following script creates a GET request for a relative link (relative to the request page) "Text.txt". It provides a function that can be invoked whenreadyState属性每次变化的时候它都将被调用,而当该属性值成为4的时候--意味着加载完成,它使用一个alert来显示responseText给用户。

Xmlhttp.open ("Get", "test.txt", true); Xmlhttp.onreadystatechange=function () {if (xmlhttp.readystate==4) {alert ( Xmlhttp.responsetext)}}xmlhttp.send (NULL)

Make a HEAD request

Sub-note: I will translate header into header, head to keep the original, resource translated into resources. The personal feeling header is more able to embody the original meaning of header. ...... Well? You don't know what the header is? This is not a newspaper head. If you understand the definition of the underlying message, you'll know that a message, whether it's an email or a text message, will have at least two parts: headers and packets, and the header contains the message, and message is the text. This is the approximate explanation, or not clear to Google it ...

For a head request, the server command returns the header of the specified resource, excluding the resource itself, which means that you can learn the Content-type or last-modified of the document without downloading a document.

A typical head request might return something similar to the following:

http/1.1 OK
Expires:sat, APR 2002 11:34:01 GMT
Date:thu, APR 2002 11:34:01 GMT
Last-modified:thu, Mar 2002 12:06:30 GMT
ETag: "0a7ccac50cbc11:1aad"

To make a head request, you just need to simply replace the first parameter with theHEAD,然后就可以使用getAllResponseHeaders获取报头或者使用getResponseHeader("Name")取得单独的报头。

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 modification time of another file.

One of the uses of the head request is to get the modification time of a URL, extend the previous example, and 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 which the head and get requests return a centralized status code, 200 represent success, 404 represent failures, and others mean something else. View the HTTP status code for a detailed explanation.xmlhttp对象使用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 ("state is" +xmlhttp.status)}}xmlhttp.send (NULL)

No flush invoke server-side script

In HTML, a form is a way to invoke a server-side script, which forces the page to refresh, which is usually not very friendly to the user. With HTTP request, you can invoke the script without refreshing the page and 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 ']. Valuexmlhttp.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 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 the ASP's JScript as the server-side language, and the HTTP accept header is used to tell the server what kind of response to send back-the full page or just the result. This HTTP accept header is used to tell the server what kind of mime-types the client will accept, and usually it will be something like that text/html . Here we tell it we only accept message/x-jl-formresult , so the server knows it is a request made by our client (or other known message/x-jl-formresult client).

Another way to determine what to return is to infer the type of data you send to the server, and you can simply submit the form to the URL of XMLHTTP request for a change. Whatever you do, it's wise to keep backward-compatible with a browser that might not support XMLHTTP request.

Using JSON as the transport language

Although XML can be used to encode (encode) the data you retrieve with this object, and throughresponseXML来访问数据,但是XML还是不能被很好的支持,一些浏览器要求资源的内容类型必须是两种可能的XML mime-type之一:text/xmlapplication/xml才能够被接受,而且你处理的XML永远可能会出现格式良好问题。JSON是一个很好的替换技术,它解析速度很快,而且,在脚本中访问,速度快得多得多。

I used JSON in my flight Routeplanner to look up flight information, such as the London Heathrow, you can easily convert the returned JSON to new Function a script object by using the initial function, which will check the state, If you find a flight from an IATA code that fails, you will return a 404 script (it checks the status as the script returns 404 if it fails to discovery Airport with this IAT a 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);

Using XMLHTTP to manipulate Google's soap APIs

Google provides a SOAP interface for its database. 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" + "<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:string ' ></restrict> <safesearch ' + ' xsi:type= "Xsd:boolean" >false</safeSearch> <lr ' + ' xsi:type= ' xsd:string ' &GT;&LT;/LR > <ie ' + ' xsi:type= ' xsd:string ' >latin1</ie> <oe ' + ' xsi:type= ' xsd:string ' >latin1</oe> ' + ' </ns1:doGoogleSearch> ' + ' </SOAP-ENV:Body></SOAP-ENV:Envelope> ')

Google is using a SOAP interface, and many people think that soap is a problem that warrants careful consideration. Rest may be a better model, because it can collaborate with the current web framework, proxies, caches, and so on. So while we can communicate with SOAP using XML HTTP request, we try not to use it until we really can't control what's happening on the server. (thank Dan Schmierer for pointing out a mistake in my script.) )

By default, this object can only callback the same server, and in a security-requiring environment (meaning access via file://), IE is able to access any domain, and Mozilla can do so, and if you make a request, you get the right permissions. (Sub-note: I will not translate the following sentence ...) What does it mean? "A Google thread I can ' t get to offline!")

Footnote 1: In fact many "Ajax" applications use this XML request object almost without using the older, but most flexible, iframe to execute remote scripting methods, but they ("Ajax" applications) can also use this object, and should develop Ajax is the idea of an application created using XML HTTP request .

Related Article

Cloud Intelligence Leading the Digital Future

Alibaba Cloud ACtivate Online Conference, Nov. 20th & 21st, 2019 (UTC+08)

Register Now >

Starter Package

SSD Cloud server and data transfer for only $2.50 a month

Get Started >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.