使用XMLHttpRequest详解

使用 XMLHttpRequest 仅仅3个步骤而已:

  • 1,Creating an XMLHttpRequest object
  • 2,Specifying and submitting your HTTP request to a web server //指定http并向一个web server提交
  • 3,Synchronously or asynchronously retrieving the server’s response //同步或异步获取服务器响应

1,创建一个XMLHttpRequest object

大部分浏览器可以用

  1. var request = new XMLHttpRequest();  
var request = new XMLHttpRequest();

Prior to Internet Explorer 7, IE does not have a native XMLHttpRequest() constructor function. In IE 5 and 6

  1. var request = new ActiveXObject("Msxml2.XMLHTTP");  
var request = new ActiveXObject("Msxml2.XMLHTTP");

或者 IE 我无语

  1. var request = new ActiveXObject("Microsoft.XMLHTTP");  
var request = new ActiveXObject("Microsoft.XMLHTTP");

下面是个跨平台创建XMLHttpRequest object的代码

  1. // This is a list of XMLHttpRequest-creation factory functions to try   
  2. HTTP._factories = [   
  3.     function() { return new XMLHttpRequest(); },   
  4.     function() { return new ActiveXObject("Msxml2.XMLHTTP"); },   
  5.     function() { return new ActiveXObject("Microsoft.XMLHTTP"); }   
  6. ];   
  7.   
  8. // When we find a factory that works, store it here.   
  9. HTTP._factory = null;   
  10.   
  11. // Create and return a new XMLHttpRequest object.   
  12. //   
  13. // The first time we're called, try the list of factory functions until   
  14. // we find one that returns a non-null value and does not throw an   
  15. // exception. Once we find a working factory, remember it for later use.   
  16. //   
  17. HTTP.newRequest = function() {   
  18.     if (HTTP._factory != nullreturn HTTP._factory();   
  19.   
  20.     for(var i = 0; i < HTTP._factories.length; i++) {   
  21.         try {   
  22.             var factory = HTTP._factories[i];   
  23.             var request = factory();   
  24.             if (request != null) {   
  25.                 HTTP._factory = factory;   
  26.                 return request;   
  27.             }   
  28.         }   
  29.         catch(e) {   
  30.             continue;   
  31.         }   
  32.     }   
  33.     // If we get here, none of the factory candidates succeeded,   
  34.     // so throw an exception now and for all future calls.   
  35.     HTTP._factory<A name=IDX-CHP-20-3497></A>   
  36.  = function() {   
  37.         throw new Error("XMLHttpRequest not supported");   
  38.     }   
  39.     HTTP._factory(); // Throw an error   
  40. }  
// This is a list of XMLHttpRequest-creation factory functions to try
HTTP._factories = [
    function() { return new XMLHttpRequest(); },
    function() { return new ActiveXObject("Msxml2.XMLHTTP"); },
    function() { return new ActiveXObject("Microsoft.XMLHTTP"); }
];

// When we find a factory that works, store it here.
HTTP._factory = null;

// Create and return a new XMLHttpRequest object.
//
// The first time we're called, try the list of factory functions until
// we find one that returns a non-null value and does not throw an
// exception. Once we find a working factory, remember it for later use.
//
HTTP.newRequest = function() {
    if (HTTP._factory != null) return HTTP._factory();

    for(var i = 0; i < HTTP._factories.length; i++) {
        try {
            var factory = HTTP._factories[i];
            var request = factory();
            if (request != null) {
                HTTP._factory = factory;
                return request;
            }
        }
        catch(e) {
            continue;
        }
    }
    // If we get here, none of the factory candidates succeeded,
    // so throw an exception now and for all future calls.
    HTTP._factory
 = function() {
        throw new Error("XMLHttpRequest not supported");
    }
    HTTP._factory(); // Throw an error
}

2,提交请求到web 服务器

  1. request.open("GET", url, false);  
request.open("GET", url, false);

false是同步相对简单先用它

open参数可以由多个,自己自定义,如密码什么的

open并没有发出请求 只是保存参数而已 在发送请求前 定义请求头部

  1. request.setRequestHeader("User-Agent""XMLHttpRequest");   
  2. request.setRequestHeader("Accept-Language""en");   
  3. request.setRequestHeader("If-Modified-Since", lastRequestTime.toString());  
request.setRequestHeader("User-Agent", "XMLHttpRequest");
request.setRequestHeader("Accept-Language", "en");
request.setRequestHeader("If-Modified-Since", lastRequestTime.toString());

Finally, after creating the request object, calling the open() method, and setting headers, send the request to the server:

  1. request.send(null);  
request.send(null);

奶奶的翻译的太痛苦了 下面的自己慢慢看

3,获取一个同步请求

The XMLHttpRequest object holds not only the details of the HTTP request that is made but also represents the server’s response. If you pass false as the third argument to open(), the send() method is synchronous: it blocks and does not return until the server’s response has arrived.[*]

[*] XMLHttpRequest has wonderfully powerful features, but its API is not particularly well designed. The boolean value that specifies synchronous or asynchronous behavior really ought to be an argument of the send() method, for example.

send() does not return a status code. Once it returns, you can check the HTTP status code returned from the server with the status property of the request object. The possible values of this code are defined by the HTTP protocol. A status of 200 means that the request was successful and that the response is available. A status of 404, on the other hand, is a “not found” error that occurs when the requested URL does not exist.

The XMLHttpRequest object makes the server’s response available as a string through the responseText property of the request object. If the response is an XML document, you can also access the document as a DOM Document object through the responseXML property. Note that the server must identify its XML documents with the MIME type “text/xml” in order for XMLHttpRequest to parse the response into a Document object.

这个同步请求 send() 后的一般检查代码

  1. if (request.status == 200) {   
  2.     // We got the server's response. Display the response text.   
  3.     alert(request.responseText);   
  4. }   
  5. else {   
  6.     // Something went wrong. Display error code and error message.   
  7.     alert("Error " + request.status + ": " + request.statusText);   
  8. }  
if (request.status == 200) {
    // We got the server's response. Display the response text.
    alert(request.responseText);
}
else {
    // Something went wrong. Display error code and error message.
    alert("Error " + request.status + ": " + request.statusText);
}

In addition to the status codes and the response text or document, the XMLHttpRequest object also provides access to the HTTP headers returned by the web server. getAllResponseHeaders() returns the response headers as an unparsed block of text, and getresponseHeader() returns the value of a named header. For example:

  1. if (request.status == 200) {  // Make sure there were no errors   
  2.     // Make sure the response is an XML document   
  3.     if (request.getResponseHeader("Content-Type") == "text/xml") {   
  4.         var doc = request.responseXML;   
  5.         // Now do something with the response document   
  6.     }   
  7. }  
if (request.status == 200) {  // Make sure there were no errors
    // Make sure the response is an XML document
    if (request.getResponseHeader("Content-Type") == "text/xml") {
        var doc = request.responseXML;
        // Now do something with the response document
    }
}

There is one serious problem with using XMLHttpRequest synchronously: if the web server stops responding, the send() method blocks for a long time. JavaScript execution stops, and the web browser may appear to have hung (this is platform-dependent, of course). If a server hangs during a normal page load, the user can simply click the browser’s Stop button and try another link or another URL. But there is no Stop button for XMLHttpRequest. The send() method does not offer any way to specify a maximum length of time to wait, and the single-threaded execution model of client-side JavaScript does not allow a script to interrupt a synchronous XMLHttpRequest once the request has been sent.

这里 主要介绍了同步的缺点,主要两点 我个人意见1,web服务器熄火了,send()要阻塞相当长时间,假死的感觉。2,不能停止请求,不能控制指定持续时间。

4,处理一个异步的响应

把open的false改成ture就为异步了

To use an XMLHttpRequest object in asynchronous mode, pass TRue as the third argument to the open() method (or simply omit the third argument: true is used by default). If you do this, the send() method sends the request to the server and then returns immediately. When the server’s response arrives, it becomes available through the XMLHttpRequest object via the same properties described earlier for synchronous usage.

An asynchronous response from the server is just like an asynchronous mouse click from a user: you need to be notified when it happens. This is done with an event handler. For XMLHttpRequest, the event handler is set on the onreadystatechange property. As the name of this property implies, the event-handler function is invoked whenever the value of the readyState property changes. readyState is an integer that specifies the status of an HTTP request, and its possible values are enumerated in The XMLHttpRequest object does not define symbolic constants for the five values listed in the table.

这里是XMLHttpRequest的readyState值 3有点问题 注意 下面的文章看我红线部分就行 其他无所谓

readyStateMeaning
0 open() has not been called yet.
1 open() has been called, but send() has not been called.
2 send() has been called, but the server has not responded yet.
3Data is being received from the server. readyState 3 differs somewhat in Firefox and Internet Explorer;
4The server’s response is complete.

Since XMLHttpRequest has only this one event handler, it is invoked for all possible events. A typical onreadystatechange handler is invoked once when open() is called and again when send() is called. It is invoked again when the server’s response starts arriving, and one final time when the response is complete. In contrast to most events in client-side JavaScript, no event object is passed to the onreadystatechange handler. You must check the readyState property of the XMLHttpRequest object to determine why your event handler was invoked. Unfortunately, the XMLHttpRequest object is not passed as an argument to the event handler, either, so you’ll have to make sure that the event-handler function is defined in a scope from which it can access the request object. A typical event handler for an asynchronous request looks like this:

  1. // Create an XMLHttpRequest using the utility defined earlier   
  2. var request = HTTP.newRequest();   
  3.   
  4. // Register an event handler to receive asynchronous notifications.   
  5. // This code says what to do with the response, and it appears in a nested   
  6. // function here before we have even submitted the request.   
  7. request.onreadystatechange = function() {   
  8.     if (request.readyState == 4) {  // If the request is finished <SPAN style="COLOR: #ff0000"><STRONG>为什么没判断1,2,3后面有解释</STRONG></SPAN>   
  9.         if (request.status == 200)  // If it was successful   
  10.             alert(request.responseText);  // Display the server's response   
  11.     }   
  12. }   
  13.   
  14. // Make a GET request for a given URL. We don't pass a third argument,   
  15. // so this is an asynchronous request   
  16. request.open("GET", url);   
  17.   
  18. // We could set additional request headers here if we needed to.   
  19.   
  20. // Now send the request. Since it is a GET request, we pass null for   
  21. // the body. Since it is asynchronous, send() does not block but   
  22. // returns immediately.   
  23. request.send(null);  
// Create an XMLHttpRequest using the utility defined earlier
var request = HTTP.newRequest();

// Register an event handler to receive asynchronous notifications.
// This code says what to do with the response, and it appears in a nested
// function here before we have even submitted the request.
request.onreadystatechange = function() {
    if (request.readyState == 4) {  // If the request is finished 为什么没判断1,2,3后面有解释
        if (request.status == 200)  // If it was successful
            alert(request.responseText);  // Display the server's response
    }
}

// Make a GET request for a given URL. We don't pass a third argument,
// so this is an asynchronous request
request.open("GET", url);

// We could set additional request headers here if we needed to.

// Now send the request. Since it is a GET request, we pass null for
// the body. Since it is asynchronous, send() does not block but
// returns immediately.
request.send(null);

The XMLHttpRequest object has never been standardized, and browsers differ in their handling of readyState 3. For example, during large downloads, Firefox invokes the onreadystatechange handler multiple times in readyState 3, to provide download progress feedback. A script might use these multiple invocations to display a progress indicator to the user. Internet Explorer, on the other hand, interprets the event handler name strictly, and invokes it only when the readyState value actually changes. This means that it is invoked only once for readyState 3, no matter how large the downloaded document is.

Browsers also differ as to what part of the server’s response is available in readyState 3. Even though state 3 means that some part of the response has arrived from the server, Microsoft’s documentation for XMLHttpRequest explicitly states that it is an error to query responseText in this state. In other browsers, it appears to be an undocumented feature that responseText returns whatever portion of the server’s response is available.

Unfortunately, none of the major browser vendors have produced adequate documentation of their XMLHttpRequest objects. Until there is a standard or at least clear documentation, it is safest to ignore any value of readyState other than 4.

讲了半天就是说着玩意不是标准的 状态3可能导致错误 解绝方案ignore any value of readyState other than 4就行
5,XMLHttpRequest的安全性

As part of the same-origin securitypolicy , the XMLHttpRequest object can issue HTTP requests only to the server from which the document that uses it was downloaded. This is a reasonable restriction, but you can circumvent it if you need to, by using a server-side script as a proxy to fetch the content of some off-site URL for you.

This XMLHttpRequest security restriction has one very important implication: XMLHttpRequest makes HTTP requests and does not work with other URL schemes. It cannot work with URLs that use the file:// protocol, for example. This means that you cannot test XMLHttpRequest scripts from your local filesystem. You must upload your test scripts to a web server (or run a server on your desktop). Your test scripts must be loaded into your web browser via HTTP in order for them to make HTTP requests of their own.

 

 

因为我的代码STYLE复制过来有问题   为了更好阅读请直接到http://www.aiice.com/291.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值