Understanding Ajax and how it works, an effective way to build a website

Source: Internet
Author: User

? XMLHttpRequest Object

One of the objects you want to know is probably the most unfamiliar to you, too XMLHttpRequest . This is a JavaScript object and it is simple to create the object, as shown in Listing 1.

Listing 1. Create a new XMLHttpRequest object
<script language= "javascript" type= "Text/javascript" >var xmlHttp = new XMLHttpRequest ();</script>

In a generic WEB application, users fill Out form fields and click the Submit button. The entire form is then sent to the server, the server forwards it to the script that handles the form (usually PHP or Java, or it could be a CGI process or something like that), and the script executes and then sends it back to the new page. The page might be HTML with a new form populated with some data, a confirmation page, or a page with some options selected based on the data entered in the original form. Of course, the user must wait while the script or program on the server processes and returns a new form. The screen becomes blank until the server returns data and then redraws. This is why interactivity is poor, and users don't get immediate feedback, so they feel different from desktop applications.

Add some JavaScript

After the resulting handle XMLHttpRequest , the other JavaScript code is very simple. In fact, we will use JavaScript code to accomplish very basic tasks:

    • Get form data: JavaScript code can easily extract data from an HTML form and send it to the server.

    • Modify the data on the form: It is also easy to update the form, from setting the field value to quickly replacing the image.

    • Parse HTML and XML: Manipulate the DOM using JavaScript code (see the next section) to work with the structure of the XML data returned by the HTML form server.

For the first two points, you need to be very familiar with the getElementById() method, as shown in Listing 2.

Listing 2. Capturing and setting field values with JavaScript code
Get the value of the "Phone" field and stuff it in a variable called Phonevar phone = document.getElementById ("Phone"). value;//Set Some values on a form using a array called Responsedocument.getelementbyid ("Order"). Value = response[0];d OCU Ment.getelementbyid ("Address"). Value = Response[1];
Listing 3. Create a XMLHttpRequest object on a Microsoft browser
var xmlHttp = false;try {  xmlHttp = new ActiveXObject ("Msxml2.xmlhttp");} catch (e) {  try {    xmlHttp = new Acti Vexobject ("Microsoft.XMLHTTP");  } catch (E2) {    xmlHttp = false;  }}
Listing 4. Create XMLHttpRequest objects in a way that supports multiple browsers
/* Create A new XMLHttpRequest object to talk to the WEB server */var xmlHttp = false;/* @cc_on @*//* @if (@_jscript_version >= 5) try {  xmlHttp = new ActiveXObject ("Msxml2.xmlhttp"),} catch (e) {  try {    xmlHttp = new ActiveXObject (" Microsoft.XMLHTTP ");  } catch (E2) {    xmlHttp = false;  }} @end @*/if (!xmlhttp && typeof XMLHttpRequest! = ' undefined ') {  xmlHttp = new XMLHttpRequest ();}

Now, regardless of the strange symbols that are commented out, for example @cc_on , this is a special JavaScript compiler command that will be XMLHttpRequest discussed in detail in the next installment of the article. The core of this code is divided into three steps:

    1. Create a variable xmlHttp to refer to the object you are about to create XMLHttpRequest .

    2. Try to create the object in a Microsoft browser:

      • Try to Msxml2.XMLHTTP create it using an object.

      • If it fails, try the Microsoft.XMLHTTP object again.

    3. If it is still not established xmlHttp , the object is created in a non-Microsoft manner.

Finally, you xmlHttp should refer to a valid XMLHttpRequest object regardless of what browser you are running.

Listing 5. Make an Ajax request
function CallServer () {  //Get the city and state from the Web Form  var city = document.getElementById ("City"). Val UE;  var state = document.getElementById ("state"). Value;  Only go on if there is values for both fields  if (city = null) | | (City = = "")) return;  if (state = = NULL) | | (state = = "")) return;  Build the URL to connect to  var url = '/scripts/getzipcode.php?city= ' + Escape (city) + ' &state= ' + Escape (state );  Open a connection to the server  xmlhttp.open ("GET", url, true);  Setup a function for the server to run when it's done  xmlhttp.onreadystatechange = updatepage;  Send the request  xmlhttp.send (null);}

Most of the code has a clear meaning. The starting code uses the basic JavaScript code to get the values of several form fields. Then set a PHP script as the target of the link. To notice how the script URL is specified, city and state (from the form) are appended to the URL with a simple GET parameter.

Then open a connection, which is the first time you see the use XMLHttpRequest . It specifies the connection method (GET) and the URL to connect to. The last parameter, if set true , will request an asynchronous connection (this is the origin of Ajax). If used false , the code will wait for the response returned by the server after making a request. If set to true , the user can still use the form (or even call other JavaScript methods) when the server processes the request in the background.

xmlHttp(Remember, this is a XMLHttpRequest property of an object instance) that onreadystatechange tells the server what to do when it finishes running (it might take five minutes or five hours). Because the code does not wait for the server, you must let the server know what to do so that you can respond. In this example, if the server finishes processing the request, a special named updatePage() method is triggered.

Finally, a value null call is used send() . Since the data to be sent to the server has been added to the request URL (city and state), no data is sent in the request. This makes a request and the server works according to your requirements.

Listing 6. Handling Server Responses
function Updatepage () {  if (xmlhttp.readystate = = 4) {    var response = Xmlhttp.responsetext;    document.getElementById ("ZipCode"). Value = response;  }}
Listing 7. Start an Ajax process
<form> <p>city: <input type= "text" name= "City" id= "City" size= "onchange=" CallServer        (); " /></p> <p>state: <input type= "text" name= "state" id= "state" size= "onchange="        callserver ();" /></p> <p>zip Code: <input type= "text" name= "ZipCode" id= "City" size= "5"/></p></form >

Understanding Ajax and how it works, an effective way to build a website

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.