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.

<script>
function CreateRequestObject()

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

var http = CreateRequestObject();

function getData()
{
http.open('get', 'info.ext')
http.onreadystatechange = handleResponse
http.send(null);
}

function handleResponse()
{
if (http.readyState == 4)
{
var data = http.responseText;
var arr = data.split("");
alert(arr[0]);
}
}

</script>
<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)
{
http.open('get', 'info.ext' + params)
http.onreadystatechange = handleResponse
http.send(null);
}


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 http.open 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!

0 Comments:

Post a Comment

<< Home