JavaScript Authority Guide Reading notes--the 18th chapter of scripted Http__java

Source: Internet
Author: User
Tags html form http post terminates
using XMLHttpRequest

Browsers define their HTTP APIs on the XMLHttpRequest class. Each instance of this class represents a separate request/response pair, and the properties and methods of this object allow you to specify request details and extract response attributes.

The first thing you have to do with this HTTP API is instantiate the XMLHttpRequest object:

var request = new XMLHttpRequest ();
the XMLHttpRequest in the IE6

In previous versions of IE, ActiveX objects were used instead of XMLHttpRequest.

if (window. XMLHttpRequest = = undefined) {
    window. XMLHttpRequest = function () {
        try{
            //if available, then return to new ActiveXObject with the latest version of the ActiveX object
            (" msxml2.xmlhttp.6.0 ");
        }
        catch (E1) {
            try{
                //Otherwise, fallback to the older version return to
                new ActiveXObject ("msxml2.xmlhttp.3.0");
            }
            catch (E2) {
                //Otherwise, error
                throw new error ("XMLHttpRequest is not supported");}
        }
    }

An HTTP request consists of 4 parts: the HTTP request method or the URL an optional request header collection an optional request body

A server returns an HTTP response that contains 3 parts: An array and a text-composed state code a response header collection response principal specify a request

After the XMLHttpRequest object is created, the next step in initiating the HTTP request is to call the XMLHttpRequest object's open () method to specify two necessary parts of the request: Method and URL.

Request.open ("Get",//an HTTP GET request
        "Index.action");//url

If there is a request header, the next step in the request error is to set it.

Request.setrequestheader ("Content-type", "Text/plain");

The final step in initiating an HTTP request using XMLHttpRequest is to specify an optional request body and send it to the server. Use the Send () method.

Request.send (NULL);
Get a response

The properties and methods of the XMLHttpRequest object status and the StatusText property return the HTTP status code in numbers and text. Use getResponseHeader () and getallresponseheaders () to query the response headers. Cannot get cookies. The response body can be obtained from the ResponseText attribute in the form of text, from the Responsexml attribute to the document form.

ReadyState is an integer that specifies the state of the HTTP request. The symbol for the first column is the constant defined by the XMLHttpRequest constructor.

Each readystate property change triggers the ReadyStateChange event. Synchronous Response

XMLHttpRequest supports synchronous responses. If you pass false as the third argument to open (), the Send () method blocks the known request completion. In this case, you do not need to use an event handler: once Send () is returned, only the status and ResponseText properties of the XMLHttpRequest object need to be checked. Response decoding

Suppose the server uses a MIME type such as "Text/plain", "text/html" or "text/css" to send a text response, and then we get it using the ResponseText property of the XMLHttpRequest object.

If the server sends an XML or XHTML document as its response, you can get a parsed XML document from the Responsexml property. The value of this property is a Document object.

If the server contains the wrong "charset" parameter in the "Content-type" header, then XMLHttpRequest will use the wrong encoding to parse the response, and the characters in responsetext may be wrong. You can use the XHR2 definition of the Overrideminetype () method to resolve the problem. To pass the type to Overridemimetype () before sending (), this will cause XMLHttpRequest to ignore the "Content-type" header and use the specified type.

Request.overridemimetype ("Text/plain; Charset=utf-8 ");
Code Request Body request for a form

The encoding scheme used for form data is relatively simple: each form element's name and value carton normal URL encoding (replaces special characters with hexadecimal escape codes), uses the equal sign to separate the encoded name and value, and uses the "&" symbol to separate the name/value pairs. A simple form is encoded as follows:

Name1=value1&name2=value2

The form data encoding format has a formal MIME type

application/x-www/urlencoded

When you use the Post method to submit this sequential form data, you must set the "Cotent-type" request header to this value. use form-coded data to initiate an HTTP POST request

function postdata (URL, data, callback) {
    var request = new XMLHttpRequest ();
    Request.open ("POST", url);
    Request.onreadystatechange = function () {
        if (request.readystate = = 4 && callback) {
            callback (Request) ;
        }
    }
    Request.setrequestheader ("Content-type", "application/x-www-urlencoded");
    The Encodeformdata () method encodes a JavaScript object as the form-passing data format
    request.send (encodeformdata (data));
}
use form encoded data to initiate an HTTP GET request
function getData (URL, data, callback) {
    var request = new XMLHttpRequest ();
    Request.open ("Get", url+ "?") +encodeformdata (data));
    Request.onreadystatechange = function () {
        if (request.readystate = = 4 && callback) {
            callback (Request) ;
        }
    }
    Request.send (null);
}
JSON-encoded request

JSON as a Web Interchange format has been popularized.

function postdata (URL, data, callback) {
    var request = new XMLHttpRequest ();
    Request.open ("POST", url);
    Request.onreadystatechange = function () {
        if (request.readystate = = 4 && callback) {
            callback ( request);
        }
    Request.setrequestheader ("Content-type", "Application/json");
    Request.send (json.stringify (data));
}
XML-encoded requests
FIMCTOPM Postquery (url,callback) {
    var request = new XMLHttpRequest ();
    Request.open ("POST", url);
    Request.onreadystatechange = function () {
        if (request.readystate = = 4 && callback) {
            callback (Request) ;
        }
    }
    Create an XML document
    var doc = document.implementation.createDocument ("", "query", null);
    var query = doc.documentelement;
    var find = doc.createelement ("find");
    Query.appendchild (find);
    Find.setattribute ("ZipCode", "value");
    Find.setattribute ("radius", "value");
    Find.appendchild (Dic.createtextnode ("text"));
    Request.send (DOC);
Uploading Files

HTML forms can always upload files, but you cannot use the XMLHttpRequest API to do the same thing. The XHR2 API then allows the upload function to be passed into the file object via the Send () method.

Without a constructor for a file () object, the script can obtain the file object of the user's current selection. In browsers that support the file object, each <input type= "file"/> element has a files attribute, which is an array object of the class of the file object.

function () {
    var elts = document.getelementsbyname ("input");
    for (var i = 0; i < elts.length i++) {
        var input = elts[i];
        if (input.type!= "file") continue;
        Input.addeventlistener ("Change", function () {
            var file = this.files[0];
            if (!file) return;
            var xhr = new XMLHttpRequest ();
            Xhr.open ("POST", "url");
            Xhr.send (file);
        }, False);
    }
Multipart/form-data Request

When an HTML form contains both file upload elements and other elements, the browser cannot use ordinary form encoding and must use a special content-type called "Multipart/form-data" to submit the form using the Post method.

XHR2 defines a new Formdata API, which is easy to implement a multiple-part Request body. First, you use the Formdata () constructor to create the Formdata object, and then call the Append () method of the object as many times as you want, to add the individual "part" to the request. Finally, the Formdata object is passed to the Send () method.

function postformdata (URL, data, callback) {
    if (typeof FormData = = "undefined")
        throw new Error ("FormData is not" Implemented ");
    var request = new XMLHttpRequest ();
    Request.open ("POST", url);
    Request.onreadystatechange = function () {
        if (request.readystate = = 4 && callback) {
            callback (Request) ;
        }
    }
    var formData = new FormData ();
    for (var name in data) {
        if (!data.hasownproperty (name))
            continue;
        if (typeof value = = = "function")
            continue;
        Formdata.append (Name,value);
    }
    Request.send (FormData);
}
HTTP Progress Events

When you call Send (), a single Loadstart event occurs. When the server's response is loading, the XMLHttpRequest object progress events, usually around 50 milliseconds, so you can use these events to give users feedback on the request event. If the request completes quickly, it may not trigger the progress event. When the event completes, the Load event is triggered.

There are 3 scenarios in which HTTP requests cannot be completed. If the request times out, the timeout event is triggered. If the request terminates, the abort event is triggered. Finally, a network error like most redirects will prevent the request from completing, triggering an error event when these conditions occur.

The draft XHR2 specification indicates that only one of the load, abort, timeout, and error triggers is triggered. The browser triggers the Loadend event.

The event associated with the Progress event has 3 useful properties loaded property is the byte value that is currently transferred the total property is the overall length (in bytes) of the data transmitted from the "Content-lenght" header, or 0 if the content length is not known The Lengthcomputable property is true to know the content length, or false

request.onprogress = function (e) {
    if (e.lengthcomputable)
        progress.innerhtml = Math.Round (100*e.loaded/ e.total) + "% Complete";
}
termination requests and timeouts

You can cancel an HTTP request that is in progress by calling the XMLHttpRequest object's Abort () method. Calling the Abort () method triggers the object's Abort event.

XHR2 defines the Timeout property to specify the number of milliseconds after the request terminates, and also defines the timeout event to trigger when a timeout occurs.

If the browser does not implement timeout, we will implement it ourselves.

function Timegettext (url,timeout,callback) {
    var request = new XMLHttpRequest ();
    var timeout = false;
    var timer = settimeout (function () {
        timeout = true;
        Request.abort ();
    }, timeout);
    Request.open ("get", url);
    Request.onreadystatechange = function () {
        if (request.readystate!== 4) return
            ;
        if (timeout) return
            ;
        Cleartimeout (timer);
        if (request.status = =)
            callback (request);
    }
    Request.send (null);
}
send HTTP requests via <script>: JSONP

<script> can be used as an AJAX transport mechanism: just set the SRC attribute of the <script> element, and then the browser sends an HTTP request to the URL that the SRC attribute points to.

When data is invoked through the <script> element, the response content must be wrapped in a JavaScript function name and parenthesis.

Handleresponse ({A: "A", B: "B"});
function Getjsonp (URL, callback) {
    var cbnum = "CB" + getjsonp.couter++;
    var cbname = "Getjsonp." + Cbnum;
    if (Url.indexof ("?") = = = 1)
        url = "jsonp=" + cbname;
    else
        URL = + "&jsonp=" + cbname;
    var script = document.createelement ("script");
    Getjsonp[cbnum] = function (response) {
        try{
            callback (response);
        }
        finally{
            Delete Getjsonp[cbnum];
            Script.parentNode.removeChild (script);
        }
    script.src = URL;
    Document.body.appendChild (script);

Getjsonp.couter = 0;
Comet technology based on server-side push event

The EventSource object simplifies the writing of the comet application by passing a URL to the EventSource () constructor and then listening for the message event on the returned instance.

var ticker = new EventSource ("url");
Ticker.onmessage = function (e) {
    var type = E.type;
    The data sent over by the server is in E.data
    var data = E.data;
}

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.