Friday, November 18, 2005

AJAX: I finally caved!

I had played a little with AJAX (Async Java and XML) but I finally caved and started to use it in an app. I must say that it is pretty freakin sweet but I am still concerned (as always with javascript) how it will behave in different browsers and operating sysystems.

function CreateRequestObject()

if (navigator.appName == "Microsoft Internet Explorer")
return new ActiveXObject("Microsoft.XMLHTTP")
return new XMLHttpRequest();

var http = CreateRequestObject();

function getData()
{'get', 'info.ext')
http.onreadystatechange = handleResponse

function handleResponse()
if (http.readyState == 4)
var data = http.responseText;
var arr = data.split("");

<a onclick="getData()" href="#">get stuff</a>

Now this is a basic example but one thing that I have done that most other samples have done is not use xml at all in this (my info.ext file contains only this: "testtest2"). I have no real need to use xml. xml would take more bandwidth, more complex code, and a dependancy on the microsoft XML parser activeXobject. Simple text parsing will do fine for me :)

If your info.ext file is a dynamic page (i.e. asp, php, jsp, etc.) and you want to pass parameters to it do this:

function getData(params)
{'get', 'info.ext' + params)
http.onreadystatechange = handleResponse

and then in the html:

<a onclick="getData('?action=getdata&id=37)" href="#">get stuff</a>

I assume that you can send post data by changing the method to post in the line and then replace the null in http.send() with the post data you want to send. I have not tried this as it is a bit more than I need.

I hope that gets you started. It really is quite easy even though js is a pain and makes me a little twitchier!


Post a Comment

<< Home