Sie sind auf Seite 1von 5

7/4/2017 AJAX|HttpWatch

(/)

HTTP Gallery

Jump to ...

11. AJAX
AJAX is a technology used by interactive web applications to make HTTP requests to a server without causing page transitions.

12.1 Introduction
In traditional web applications, the browser renders a series of HTML pages which directly result from server operations. This is essentially a
more sophisticated version of the 'dumb terminal' models used by earlier mainframe applications.

Each time a user enters some data and submits a form, the browser makes a call to the server so that it can perform some operation or
calculation. The results of that call are rendered in HTML and displayed as a new page:

(/images/webapp.png)

The use of AJAX allows JavaScript on a web page to issue HTTP requests to a server without ever leaving the page. Modern, interactive web
applications use this technique to update the web page without causing the distracting icker that is seen when the browser loads a new page.

A typical example might be a shopping site with a cart that can be updated without leaving the page:

(/images/webapp.png)

The data returned from an AJAX call does not have to be in HTML format, because it is not automatically rendered by the browser. Instead, it is
parsed in JavaScript and appropriate changes are made to page to display the data.

https://www.httpwatch.com/httpgallery/ajax/ 1/5
7/4/2017 AJAX|HttpWatch
AJAX stands for Asynchronous JavaScript And XML because early implementations often used XML as the data format. Since then, simpler more
e cient formats such as JSON (JavaScript Object Notation) have gained popularity.

12.2 Making an AJAX call


The core functionality of AJAX is implemented in the XmlHttpRequest object that is now incorporated in most modern browsers. The sample
code, shown below, makes a call to the web server to obtain the data to display in a list box. The response data is in HTML format for the sake of
simplicity because it allows the text returned from the server to be applied directly to the <div> tag.

<scripttype="text/javascript">
functionGetShoppingList()
{
//CreateaninstanceoftheHTTPrequestobject
varxmlHttp=newXMLHttpRequest();

//SpecifyHTTPGETbydefaultandsupplytherelativeurl
xmlHttp.open("GET","getlist.aspx",false);

//StartasynchronousAJAXrequestandwait
//fortheresponse
xmlHttp.send(null);

vartargetNode=document.getElementById("divShoppingList");

//UsetheHTMLreturnedfromservertocreatelist
targetNode.innerHTML=xmlHttp.responseText;
}
</script>

<form>
<inputonclick="GetShoppingList();"type="button"value="FetchList"/>
<divid="divShoppingList"></div>
</form>

A working demonstration of this code is shown below in Example 12

Example 12
Populate a List Box using AJAX

Click on 'Fetch List' to download a shopping list from the server:

FETCH LIST

12.3 Sending Parameters with AJAX


AJAX is often styled as an RPC (http://en.wikipedia.org/wiki/Remote_procedure_call) mechanism in which some kind of parameter list is
constructed for a server-side call and the results are returned in a convenient format such as XML, CSV or JSON (http://www.json.org/).

The code below shows how two numeric parameters can be passed to a server using a simple comma delimited format. The encoded
parameters are supplied as a string parameter to the send method and become the payload of the resulting HTTP POST request message:

https://www.httpwatch.com/httpgallery/ajax/ 2/5
7/4/2017 AJAX|HttpWatch

<scripttype="text/javascript">
functionAddNumbers()
{
//CreateaninstanceoftheHTTPRequestObject
varxmlHttp=newXMLHttpRequest();

varvalue1=document.getElementById("txtValue1").value;
varvalue2=document.getElementById("txtValue2").value;

//SpecifyHTTPPOSTsothatparameterscanbepassedin
//requestbody
xmlHttp.open("POST","add.aspx",false);

//SendtheparametersinCSVformat
xmlHttp.send(value1+","+value2);

varresult=document.getElementById("spanResult");

//Useresultofcalculationfromserver
result.innerHTML=xmlHttp.responseText;
}
</script>

<form>
<inputid="txtValue1"/>
<inputid="txtValue2"/>
<inputonclick="AddNumbers();"type="button"value="Add"/>

<p>Result:</p>
<spanid="spanResult"></span>
</form>

Example 13 shows a working version of this code:

Example 13
Pass two parameters with AJAX

Click on 'Add' to display the sum of the two numbers entered:

32 48 ADD

Result is:

12.4 Using AJAX with a JavaScript Library


There are a number of issues with AJAX that have been ignored in the previous sections:

Some older browsers do not natively support the XmlHttpRequest object. For example, in IE 6 you have to use ActiveXObject("Msxml2.XMLHTTP") to
create an XmlHttpRequest object.

Any use of AJAX requires error handling code so that meaningful errors are displayed to the user. This is not a straightforward task because the server
may return success codes other than '200 OK', or dierent classes of failure.

AJAX calls can be made asynchronously so that the web application remains responsive even if a call to the server takes several seconds. Handling this
asynchronous mode of operation is fairly involved as it requires the use of a callback function and querying the value of the readystate property.

Given these challenges most developers use a library to handle the cross-browser issues and simplify what is essentially 'boilerplate' code. One
of the most widely used is jQuery (http://jquery.com/) which provides AJAX support as well as many other features.

Let's see how we could re-work one of our earlier examples using jQuery. Almost any HTML element can be the target recipient of an AJAX
request in jQuery a. If our server returns HTML we can simply bind our <div> output tag directly as shown below:

https://www.httpwatch.com/httpgallery/ajax/ 3/5
7/4/2017 AJAX|HttpWatch

functionjQueryGetShoppingList()
{
//$couldbeusedasanaliasforjQuery:
//
//$("#divShoppingList").load("getlist.aspx");
//
jQuery("#divShoppingList").load("getlist.aspx");
}

Example 14 shows a working version of this code:

Example 14
Populate a List Box using AJAX and jQuery

Click on 'Fetch List' to download a shopping list from the server::

FETCH LIST

Using HttpWatch with Examples 12, 13 & 14

HttpWatch will show the AJAX requests made by the demos on this page:

1. Open HttpWatch by right clicking on the web page and selecting HttpWatch from the context menu

2. Click on Record to start logging requests in HttpWatch

3. Use the Examples 12 - 14 to see how AJAX requests are recorded in HttpWatch

<11. HTTPS (../HTTPS/)

Ready to get started?

TRY FOR FREE

(/DOWNLOAD/)
BUY NOW (/BUY/)

HttpWatch
Features (/features/httpdebugger.aspx)
Compare Editions (/editions.aspx)
New in Version 10.x (/newin10x.aspx)
Download (/download/)
Pricing (/buy/)

Our Customers
Who is using it? (/#customers)
What are they saying? (/#quotes)

Learning & Documentation

HttpWatch Blog (http://blog.httpwatch.com)


https://www.httpwatch.com/httpgallery/ajax/ 4/5
7/4/2017 AJAX|HttpWatch
HttpWatch Blog (http://blog.httpwatch.com)
HTTP Gallery (/httpgallery/)
HttpWatch Help (http://help.httpwatch.com)
HttpWatch Automation Reference (http://apihelp.httpwatch.com)

Support
Technical Support (/support/)
About Us (/company/)
Contact Us (/company/)
Blog (http://blog.httpwatch.com)
Twitter (https://twitter.com/httpwatch)

Search (/search/) Terms & Conditions (/company/terms.aspx) Privacy Policy (/company/privacy_policy.aspx) Copyright (/company/copyright.aspx)

Copyright 2017 Neumetrix Limited (/)

https://www.httpwatch.com/httpgallery/ajax/ 5/5

Das könnte Ihnen auch gefallen