Ajax Asynchronous callback mechanism __ajax

Source: Internet
Author: User
Tags object model tld

what is Ajax.

Ajax, "Asynchronous JavaScript and XML" (Asynchronous JavaScript and XML), is a web development technology that creates interactive Web applications.

Mainly includes the following technologies:

-A representation based on the Web Standard (standards-based presentation) xhtml+css;

. Use DOM (Document Object Model) for dynamic display and interaction;

Use XML and XSLT for data exchange and related operations;

Using XMLHttpRequest for asynchronous data query and retrieval;

. Use JavaScript to bind all things together.

Two powerful features of Ajax:

. You can send requests to the server without reloading the entire page.

Parsing and processing of XML documents.

Step "Please!"---how to send an HTTP request

(1) In order to send an HTTP request to the server with JavaScript, a class instance with this function is required. Such classes are first introduced by Internet Explorer as ActiveX objects, known as XMLHTTP.

Later Mozilla, Safari and other browsers followed suit, providing the XMLHttpRequest class, which supports the methods and properties provided by Microsoft's ActiveX objects.

Therefore, in order to create a cross browser class instance (object), you can apply the following code:

if (window. XMLHttpRequest) {//Mozilla, Safari, ...
Http_request = new XMLHttpRequest ();
else if (window. ActiveXObject) {//IE
Http_request = new ActiveXObject ("Microsoft.XMLHTTP");
}

(The previous example simplifies the code to explain how to create an instance of the XMLHTTP class.) The actual code instance can be read in this step 3.

(2) If the server's response does not have an XML Mime-type header, some Mozilla browsers may not work correctly. To solve this problem, if the header of the server response is not text/xml,

Other methods can be invoked to modify the header.

Http_request = new XMLHttpRequest ();
Http_request.overridemimetype (' Text/xml ');

(3) Next decide what you want to do when you receive a response from the server. This tells the HTTP request object which JavaScript function to use to handle the response.

You can set the object's onReadyStateChange property to the name of the JavaScript function you want to use, as follows:

Http_request.onreadystatechange = nameofthefunction;

Note: There is no parentheses after the function name, and there is no need to pass parameters. There is also a way to define a function and the behavior it will take in response, as follows:

Http_request.onreadystatechange = function () {
Do the Thing
};

(4) When the response is defined, the request is sent. You can invoke the open () and send () methods of the HTTP request class as follows:

Http_request.open (' Get ', ' http://www.example.org/some.file ', true);
Http_request.send (NULL);

The first parameter of the. Open () is the way that HTTP request –get, POST, head, or any server support you want to invoke.

This argument is capitalized according to the HTTP specification, otherwise some browsers, such as Firefox, may not be able to process the request.

. The second parameter is the URL of the request page. The page cannot be a third party domain name due to the limitations of its own security features. Be sure to use the exact domain name on all pages,

Otherwise, calling open () gets the "permission denied" error prompt. A common mistake is to use domain.tld when visiting a site, but to use WWW.DOMAIN.TLD when requesting a page.

. The third parameter sets whether the request is asynchronous mode. If true, the JavaScript function continues to execute without waiting for the server to respond. This is "A" in "AJAX".

If the first argument is "POST", the parameter of the Send () method can be any data that you want to send to the server. The data is then sent to the server as a string, as follows:

Name = value & anothername = othervalue & so = On

If the first argument is "get", the parameter of the Send () method is null.

step 2– "Receive!"---processing server response

When sending a request, provide the name of the JavaScript function that specifies the response to be processed.

Http_request.onreadystatechange = nameofthefunction;

(1) Let's see what the function of this function is. The function first checks the state of the request. If the status value is 4, it means that a full server response has been received and you will be able to handle the response.

if (http_request.readystate = = 4) {
Everything is good, the response is received
} else {
Still not ready
}

The readyState values are as follows:

0 (uninitialized) 1 (loading) 2 (load complete) 3 (interactive) 4 (complete)

(2) The function then checks the status value of the HTTP server response. We focus on the response value of the OK.

if (Http_request.status = = 200) {
perfect!
} else {
There was a problem with the request,
For example the "response may" a 404 (Not Found)
or (Internal Server Error) Response codes
}

(3) After checking the status value of the request and the HTTP status value of the response, you can process the data obtained from the server. There are two ways to get this data:

. http_request.responsetext– returns the response of the server as a text string

. http_request.responsexml– returns the response as a XmlDocument object. Processing XmlDocument objects can be used with JavaScript DOM functions

step 3– "Everything is ready!"-simple example

Attached is a simple and complete asynchronous callback function MakeRequest (URL, functionname, Httptype, SendData):

Ajax POST Request
Defining XMLHttpRequest Object Instances
var http_request = false;
/* ************************************************************************
* Method Description: Reusable HTTP request send function
* Parameter Description:
* URL: Destination URL
* functionname: function to callback
* Httptype: Request method (Get/post)
* SendData: The data that you want to pass to the server when you post the request.
* Data is listed as a query string, such as: Name=value&anothername=othervalue.
* If you use Get method: please send null
************************************************************************ */
function makerequest (URL, functionname, Httptype, SendData) {

Http_request = false;
if (! Httptype) Httptype = "Get";

if (window. XMLHttpRequest) {//Non-ie ...
Http_request = new XMLHttpRequest ();
if (Http_request.overridemimetype) {
Http_request.overridemimetype (' Text/xml ');
}
else if (window. ActiveXObject) {//IE
try {
Http_request = new ActiveXObject ("Msxml2.xmlhttp");
catch (e) {
try {
Http_request = new ActiveXObject ("Microsoft.XMLHTTP");
catch (e) {}
}
}

if (! Http_request) {
Alert (' Cannot send an XMLHTTP request ');
return false;
}

Http_request.onreadystatechange = functionname;
Http_request.open (Httptype, URL, true);
Http_request.setrequestheader (' Content-type ', ' application/x-www-form-urlencoded ');
Http_request.send (SendData);
}

(1) We will now complete the whole process once, send an HTTP request. We request a ORDERDELIVERY.ASHX server file with JavaScript on the client orderdelivery.js

function Enterproductbarcode (ordergoodsid,ordernumber) {
......
var requesturl = ". /javascript/orderdelivery.ashx?function=enterproductbarcode&ordergoodsid= "+ OrderGoodsID +" &OrderNumber= "+ OrderNumber +" &productbarcode= "+ productbarcode;
MakeRequest (Requesturl,enterproductbarcodeback, "POST", null);
}

(2) ORDERDELIVERY.ASHX receives the Requesturl and executes the corresponding function based on the value of the function parameter. After execution, returns the callback function for the data to the client.

public void ProcessRequest (HttpContext context) {
string function = Context. request.params["function"];
try {
if (function = = "Enterproductbarcode") {
Context. Response.Write (.....) This returns the callback function of the data to the client ...);
return;
}
if (...) {......}
}
catch (Exception e)
{
Context. Response.Write (E.message);
}
}

(3) The callback function of the client Orderdelivery.js Enterproductbarcodeback uses Http_request.responsetext to obtain the data returned by the server side. and processed.

function Enterproductbarcodeback () {
var str = Http_request.responsetext;
if (http_request.readystate = = 4) {
if (Http_request.status = = 200) {
... Handling str ...
}
}
}

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.