锘??xml version="1.0" encoding="utf-8" standalone="yes"?>
Using getElementsByTagName, we iterate thru the XML tree and read the numerous children/sibling.
<html>
<body>
<script>
var xmlstring = '<?xml version=\"1.0\"?>\
<shoppingcart date="14-10-2005" total="123.45">\
<item code="12345">\
<name>Widget</name>\
<quantity>1</quantity>\
</item>\
<item code="54321">\
<name>Another Widget</name>\
<quantity>2</quantity>\
</item>\
</shoppingcart>';
// convert the string to an XML object
var xmlobject = (new DOMParser()).parseFromString(xmlstring, "text/xml");
// get the XML root item
var root = xmlobject.getElementsByTagName('shoppingcart')[0];
var date = root.getAttribute("date");
alert("shoppingcart date=" + date);
var items = root.getElementsByTagName("item");
for (var i = 0 ; i < items.length ; i++) {
// get one item after another
var item = items[i];
// now we have the item object, time to get the contents
// get the name of the item
var name = item.getElementsByTagName("name")[0].firstChild.nodeValue;
// get the quantity
var quantity = item.getElementsByTagName("quantity")[0].firstChild.nodeValue;
alert("item #" + i + ": name=" + name + " quantity=" + quantity);
}
</script>
</body>
</html>
Example #2:
Here is a more universal example with the method "childNodes".
<html>
<body>
<script>
var xmlstring = '<?xml version="1.0"?>\
<root>\
<data>\
<row>\
<cell>Admiral</cell>\
<cell>Melon</cell>\
<cell>Carrot</cell>\
</row>\
<row>\
<cell>Captain</cell>\
<cell>Banana</cell>\
<cell>Zucchini</cell>\
</row>\
</data>\
<data>\
<row>\
<cell>Midshipman</cell>\
<cell>Orange</cell>\
<cell>Potatoe</cell>\
</row>\
</data>\
</root>';
// convert the string to an XML object
var xmlobject = (new DOMParser()).parseFromString(xmlstring, "text/xml");
// get the XML root item
var root = xmlobject.getElementsByTagName('root')[0];
for (var iNode = 0; iNode < root.childNodes.length; iNode++) {
var node = root.childNodes.item(iNode);
for (i = 0; i < node.childNodes.length; i++) {
var sibling = node.childNodes.item(i);
for (x = 0; x < sibling.childNodes.length; x++) {
var sibling2 = sibling.childNodes.item(x);
if (sibling2.childNodes.length > 0) {
var sibling3 = sibling2.childNodes.item(0);
alert(sibling3.data);
}
}
}
}
</script>
</body>
</html>
]]>
You could build an XML document out of your recordset and send that back to the server, say you had a redord set for a "user" with the following details (name, surname, age, email), you could build an xml document like this:
Code:
<recordset>
<user>
<name>Byron</name>
<surname>Tymvios</surname>
<age>25</age>
<email>email@address.com</email>
</user>
<user>
<name>User</name>
<surname>Someone</surname>
<age>39</age>
<email>myAddy@address.com</email>
</user>
</recordset>
You can add as many records as you have in your recordset, then once the client has received it you can use javascript to iterate over the <user>'s in the xml.
var saveState = true;
if(saveState)
{
// This AJAX call will save the Navigator's state to session.
// We don't need a callback function because nothing happens
// once said state is saved.
var url = "AJAX_Servlet.aspx?function=saveNavigatorState&control=" + id + "&class=" + section.className + "";
req = new ActiveXObject("Microsoft.XMLHTTP");
req.open("POST", url, true);
req.send();
}
private void Page_Load(object sender, System.EventArgs e)
{
if(Request.QueryString["function"] != null)
{
if(Request.QueryString["function"] == "saveNavigatorState")
SaveNavigatorState();
}
}
private void SaveNavigatorState()
{
if(Request.QueryString["control"] != null && Request.QueryString["class"] != null)
{
string controlID = Request.QueryString["control"].ToString();
string className = Request.QueryString["class"].ToString();
Session[controlID] = className;
}
}
Questions:
- Entry level:
聽 - Is AJAX a programming language?
聽 - What is AJAX?
聽 - How new is AJAX?
聽 - Why can/should AJAX be used?
聽A: AJAX is best suited for small (hopefully unobtrusive) updates to the current
聽 聽 web page, based on information that is not available until it has been provided
聽 聽 by the end user.
聽 - When should AJAX NOT be used?
聽 A: It would not be appropriate to use AJAX when the "answer/result" can be determinded
聽 聽 by the client. 聽Generally, the purpose of AJAX is to submit a short request to the server,
聽 聽 and process the response in such a way as to add value to the currently displayed page.
聽 聽 It would also not be appropriate to use AJAX when the magnitude of the response is such
聽 聽 that it would be easier, and more clear to redisplay the page.
聽 - What objects are used by AJAX programs?
- Intermediate-level?
聽 - Describe the 聽formats and protocols used/specified by AJAX
聽 - Describe some things that can't be done with AJAX
聽A: Sending a request to a server outside of the domain from which聽 the web page originated.
聽 - How should AJAX objects be created?
聽 - For what error conditions should programs check?
聽 - Are Finite State Machines (FSM's) appropriate for use with AJAX?
聽 - Identify and describe the state transitions that can/should occur within a transaction
A: - Reset : When the XmlHttpRequest object is created, no connection yet exists between the clent, and the server.
聽 聽 聽 Open 聽: When the xmlHttp.open() is issued, the request is being prepared for transmission to the server
聽 聽 聽 Sent 聽 : When the xmlHttp.send() is issued, the request is transmitted to the server application
聽 聽 聽 Rcvd 聽 : When the xmlHttp callback routine is called, the readyState and status fields of the object define why the routine was called
Q. How do you know that an AJAX request has completed?
A. The XHR.readyState is 4 and the XHR.status is 200 (or zero if the request is to a local file). The callback function is called four times - first with status=1, then 2,3, and finally 4.
Q. How does XML processing differ on the different browsers?
A. It's an ActiveX object on IE, but is native on the other browsers
Q: What values exists for the XmlHttpRequest.readyState field, and what do they mean?
A: readyState values:
聽 聽 0 = uninitialized
聽 聽 1 = loading
聽 聽 2 = loaded
聽 聽 3 = interactive
聽 聽 4 = complete聽聽
Other areas to check up on:
聽 聽How do you process the returned XML data?
聽 聽If it's a Java/J2EE place: what about AJAX and JSF?
聽 聽How to populate the XML response on the server?
聽 聽How to terminate an active request?
Using AjaxPage update without refresh using Javascript, PHP and XML's聽XMLHTTPRequest object (also known as 'remote scripting')In this tutorial we'll discuss the basic principles of remote scripting using Ajax, a combination of javascript and XML to allow web pages to be updated with new information from the server, without the user having to wait for a page refresh.聽 Ajax therefore allows us to build web applications with user interfaces rather more like those of desktop applications, providing a better experience for the user.聽 Ajax tools are becoming increasingly popular, and a list of ajax development projects is also given. Here you'll find:
This tutorial covers subjects which require some degree of familiarity with Javascript and PHP.聽 Beginners may therefore find it a little hard going, but hopefully should still be able to grasp the principles and uses聽of Ajax, if not the details.聽 There are some demos and further links at the bottom of the article and elsewhere on these pages - feel free to explore..
What is it?
This is at times frustrating for the user, besides being rather different to the 'desktop' style of user interface with which (s)he may be more familiar. Ajax (Asynchronous Javascript And XML) is a technique (or, more correctly, a combination of techniques) for submitting server requests 'in the background' and returning information from the server to the user without the necessity of waiting for a page load. Ajax is actually a combination of several technologies working together to provide this capability.
How does it work?
Although this object may be unfamiliar to many, in fact it behaves like a fairly ordinary javascript object.聽 As you may well know, when using a javascript image object we may dynamically change the URL of the image source without using a page refresh. XMLHTTPRequest retrieves information from the server in a similarly invisible manner.
How is it coded? Firstly, we need to know how to create an XMLHTTPRequest object.聽 The process differs slightly depending on whether you are using Internet Explorer (5+)聽with ActiveX enabled, or a standards-compliant browser such as Mozilla Firefox. With IE, the request looks like: http = new ActiveXObject("Microsoft.XMLHTTP"); whereas in a standards-compliant browser we can instantiate the object directly:
http = new
XMLHttpRequest();
There's an example of a short piece of code to create the object here, which clearly demonstrates the different approaches for the two different browser types, along with a browser detection routine. Secondly, we need to write an event handler which will be called via some event on our user's page, and will handle sending our request for data to our server. The event handler will use various methods of our XMLHTTPRequest object to:
We can make our request of the server by using a GET method to an appropriate server-side script.聽 Here's an example event handler called聽updateData which assumes that we have created our XMLHTTPRequest object and called it聽http:
function updateData(param) { 聽聽 http.open("GET",聽myurl + "?id=" + escape(param), true ); 聽 http.onreadystatechange = useHttpResponse; 聽 http.send(null); } 聽 Note that the function listens to the onreadystatechange property of the XMLHTTPRequest object and, each time this parameter changes, calls a further function useHttpResponse. You will note also that, for the sake of clarity,聽I have said little about the server-side script which is called - essentially this can be any server routine which will generate the required output when called with the relevant URL and appended parameters, as in any other HTTP GET request.聽 For the sake of the example we are passing a variable named id with a value param passed as an argument to the updateData function. Thirdly, then, we need to write a function useHttpResponse which will establish when the server has completed our request, and do something useful with the data it has returned:
function
useHttpResponse() { Note here that our function checks for a readyState value of 4 - there are various numbered states describing the progress of such a request, but we are only interested in the value of 4, which indicates that the request is complete and we can use the returned data. In this case, we have received our information as simple text via the responseText property of our XMLHTTPRequest object.聽 Information can, however, be returned as XML or as properties of a predefined javascript object, though this is perhaps beyond the scope of this tutorial. Try out all the techniques described above in the Ajax Demonstration Making Ajax Easy There are quite a few toolkits springing up that package the Ajax calls into useable libraries.聽 For small projects, these may not be worth using due to the code overhead and learning curve involved, but for more complex Ajax projects you may find them useful.聽 You'll find some relevant links below and elsewhere on these pages - feel free to explore. |