Using AJAX to implement client-server communication in JavaScript (ix)

Source: Internet
Author: User

One: Ajax (asynchronous JavaScript and XML) is not a new technology, in fact, it is some old mature technology in a new and more powerful way to integrate together

Key Technologies for Ajax: 1. Using XHTML (HTML) and CSS to build a standardized presentation Layer 2. Use the DOM for dynamic display and interaction 3. Data exchange and manipulation using XML and XSLT 4. Use XMLHttpRequest to asynchronously get data 5. Use JavaScript to bind all elements together Two: How to write AJAX applications: First step: Create a XMLHTTP Object

Second request step: After creating the XML HTTP request object, you can use the open () method to specify the

Orequest.open ("Get", "Example.txt", false);

The method has three parameters:

1. Type of request to send: GET, POST, header, etc.

2. URL of the request

3, asynchronous (true), or synchronous (false)

Orequest.open ("Get", "Example.txt", false);

The method has three parameters:

1. Type of request to send: GET, POST, header, etc.

2. URL of the request

3, asynchronous (true), or synchronous (false)

If you are sending an asynchronous request, you must use the Onreadystatechage event handler and check that the readystate attribute is equal to 4 (as with the XML DOM), and the response object is not available until the request is complete:
JScript file function createhttprequest () {var arrsignatures = ["MSXML2. xmlhttp.5.0 "," MSXML2. xmlhttp.4.0 "," MSXML2. xmlhttp.3.0 "," MSXML2.                                 XMLHTTP "," Microsoft.XMLHTTP "]; for (var i=0; i < arrsignatures.length; i++) {try {var orequest = new ActiveXObject                            (Arrsignatures[i]);                    return orequest; } catch (Oerror) {//ignore}} throw new Error ("MSXML is not installed     On your system. ");}  var Http = new Object ();     Http.get=function (url,fnloading,fncallback) {var orequest = createhttprequest (); if (orequest) {Orequest.open ("get", url,true);
Set the callback function Orequest.onreadystatechange = function () {if (orequest.readystate = = 4) {
A successful callback returns the data to if (Fncallback) fncallback (Orequest.responsetext); }else {if (fnloading) fnloading (); }} orequest.send (null); } }

HTML page:

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">

C # code for the page requested by the background:

System.Threading.Thread.Sleep (2000);
Response.Write ("OK");

Third: Use HTTP header

Each HTTP request is sent with a set of headers with additional information. When we use the browser, these headers are hidden because the information is useless to the end user. However, these first messages may be important to the developer

1. getAllResponseHeaders () method

HTTP header information for returning all responses

2, getResponseHeader ("parameter")

Used to get a specified header

3, setRequestHeader ("MyHeader", "value");

Header information for setting the XML HTTP request

An HTTP request is as follows: server:microsoft-iis/5.1 Date:mon, 14:46:05 GMT x-powered-by:asp.net x-aspnet-version:2.0.507 Cache-control:private

Content-type:text/xml; Charset=utf-8

content-length:15812

Orequest.getallresponseheaders ()//Get the above information

Orequest.getresponseheader ("Content-type")

Text/xml; Charset=utf-8

Orequest.setrequestheader ("MyHeader", "myvalue");

Here you can assume that you have designed some server logic to provide additional functionality based on these header information or to compute the request

Making a POST request

As with get requests, the parameters of the post request must also be encoded and split with &, although this parameter is not appended to the URL, and the parameter is passed to the Send () method when the POST request is sent:

Orequst.open ("Post", "http://www.myweb.com/login.aspx", false);

Orequest.send ("username=admin&password=123");

Note: When using the Post method in and AJAX requests: the request "Content-type" header must be set to "application/x-www-form-urlencoded", so:

Orequst.open ("Post", "http://www.myweb.com/login.aspx", false);

Orequst.setrequestheader ("Content-type", "application/x-www-form-urlencoded");

Orequest.send ("username=admin&password=123");

A small instance login:

<%@ page language= "C #" autoeventwireup= "true" codefile= "Login.aspx.cs" inherits= "Login"%><! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd    ">

Background code:

public partial class loginhandler:system.web.ui.page{    protected void Page_Load (object sender, EventArgs e)    { C2/>if (request["user"] = null && request["password"]! = null)        {            string user = request.querystring[" User "];            string password = request.querystring["password"];            if (user = = "Admin" && password = = "123")                Response.Write ("Success");            else                Response.Write ("Error");}}}    

Four: Json

JSON sample

The following JSON represents a name/value pair: {"FirstName": "Brett"} multiple name/value pairs are strung together: {"FirstName": "Brett", "LastName": "McLaughlin", "email": "[email Protected] "}

In terms of syntax, this has no significant advantage over name/value pairs, but in this case the JSON

Easier to use and more readable

When you need to represent a set of values, JSON not only improves readability, but also reduces complexity:

{"Employees": [

{"FirstName": "Brett", "LastName": "McLaughlin", "email": "[email protected]"},

{"FirstName": "Jason", "LastName": "Hunter", "email": "[email protected]"},

{"FirstName": "Elliotte", "LastName": "Harold", "email": "[email protected]"}

] }

This is more concise than the data represented in the corresponding XML format:

The corresponding XML format: <employees>     ?< employee >          ?<firstname>brett</firstname>         ?<lastname>mclaughlin</lastname>?          < email>[email protected]</email>?     </Employee >?       < employee >?           <firstName> jason</firstname>?          <lastName>Hunter</ lastname>?          <email>[email protected]</ email>?    </Employee >?     < employee >?             <firstName>Elliotte</firstName>?            <lastName>Harold</lastName>          ?<email>[email protected]</email>?     </employee></ Employees > xml and JSON comparison: readability JSON and XML are comparable readability, XML slightly the upper hand extensibility of XML is inherently very good extensibility, json of course, there is no XML can be extended, JSON can not. Coding difficulty XML has a wealth of coding tools, such as dom4j, jdom, etc. JSON also has json.org provides tools, but JSON encoding is significantly easier than XML, even if the use of tools can also write JSON code, but to write good XML is not easy to decode the difficulty of XML parsing to consider the child node parent node relationship, make people dizzy, and JSON parsing difficulty is almost zero. The popularity of XML has been widely used in the industry, and JSON has just begun, but in the Ajax realm, JSON with its own advantage may eventually replace Xml json is the JavaScript native format, This means that working with JSON data in JavaScript does not require any special APIs or toolkits. To assign the JSON data to a variable:

var company =

{"Employees": [

{"FirstName": "Brett", "LastName": "McLaughlin", "email": [email protected] "},

{"FirstName": "Jason", "LastName": "Hunter", "email": "[email protected]"},

{"FirstName": "Elliotte", "LastName": "Harold", "email": "[email protected]"}

]

}; This will create a JavaScript object

Access data as a JavaScript object, such as obtaining FirstName information for the first employee: Company.employees[0].fristname just as you can access data with dots and parentheses, You can also easily modify the data in the same way: Company.employees[0].fristname= "Vincent" The server side returns the JSON corresponding text representation, such as: {"City": "Hefei", "Province": " Anhui "} Clients use the Eval () function to convert JSON text into JavaScript objects: Use extra parentheses to make the eval () function parse the source input unconditionally as an expression. Then get the corresponding value from the JavaScript object: Own the instance code of the Ajax:
var http={xmlhttprequest:function () {try {var orequest = new XMLHttpRequest ();        return orequest; }catch (ex) {var arrsignatures = ["MSXML2. xmlhttp.5.0 "," MSXML2. xmlhttp.4.0 "," MSXML2. xmlhttp.3.0 "," MSXML2.                                                 XMLHTTP "," Microsoft.XMLHTTP "]; for (var i=0; i < arrsignatures.length; i++) {try {var oreq                                            Uest = new ActiveXObject (arrsignatures[i]);                                    return orequest; } catch (Oerror) {//ignore}}} throw new ERR                    or ("MSXML is not installed on your system.");         }, Get:function (sURL, fncallback,fnloading) {var orequest = new Http.xmlhttprequest ();   Orequest.open ("Get", sURL, True); Orequest.onreadystatechange = function () {if (orequest.readystate = = 4) {if (Fncall                back) Fncallback (Orequest.responsetext);                }else if (fnloading)//call loading function ...                {if (fnloading) fnloading ();                 }} orequest.send (null);     }}


Using AJAX to implement client-server communication in JavaScript (ix)

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.