Following codes is the minimum 4 steps for XMLHttpRequest.
<script language="javascript">
////////////////// initial xmlhttprequest ///////////////////////////
// 1. new XMLHttpRequest()
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
}
else{
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
alert('Old Microsoft.XMLHTTP activexobject before IE 5.5');
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
////////////////// configure and get xmlhttprequest ///////////////////////////
try{// this try/catch is only for firefox: if you installed firebug,disable it.
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
//netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
}catch (e){}
// 2. request.open()
try{
//req.open("GET", "http://crosszheng.spaces.live.com/feed.rss", true);
req.open("GET", "feed.rss", true);
//alert('get successfully');
}
catch(e){
alert(e.toString());
}
// 3. define request.onreadystatechange function, which is a event handler.
req.onreadystatechange = function() {
try
{
if((req.readyState == 4) && (req.status == 200))
{
try{
xmlobject = (new DOMParser()).parseFromString(req.responseText, "text/xml");
}catch(e){
xmlobject=new ActiveXObject("Microsoft.XMLDOM");
xmlobject.async="false";
xmlobject.loadXML(req.responseText);
}
// get a reference to the root-element "rss"
var root = xmlobject.getElementsByTagName('rss')[0];
// get reference to "channel" element
var channels = root.getElementsByTagName("channel");
// now get all "item" tags in the channel
var items = channels[0].getElementsByTagName("item");
// in the "item" we have a description, so get that
var descriptions = items[0].getElementsByTagName("description");
var desc = descriptions[0].firstChild.nodeValue;
document.write(desc);
document.close();
}
}
catch(e){
alert(e.toString());
}
}
// 4. request.send(null)
req.send(null);
</script>
more details on:http://developer.apple.com/internet/webcontent/xmlhttpreq.html
Friday, 7 March 2008
retrive XML in ajax way: xmlhttprequest
at 12:49
labels: howto, JavaScript
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment