I hate the term “ajax” and I mostly refuse to use it… So I will refrain here.
The following javascript provides the basic/core functionality for all modern web applications: the asynchronous HTTP request.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | function doHttpRequest( strUrl, objRequestData, bDoPost, callback ) { var xmlhttp = new XMLHttpRequest(); if (!xmlhttp) { alert( 'Your browser is too old... Sorry.' ); } else { var strRequestData = "" ; for ( var strKey in objRequestData ) { var strValue = objRequestData[strKey]; if ( strRequestData.length>0 ) { strRequest += "&" ; } strRequestData += encodeURIComponent(strKey) + "=" + encodeURIComponent(strValue); } xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4) { if ( xmlhttp.status!=200 ) { alert( "Error in HTTP Request...\n\nStatus: " +xmlhttp.status+ "\n" +xmlhttp.statusText); } else { var cbParams = { 'xmlhttp' :xmlhttp }; callback(cbParams); } } } if ( bDoPost ) { xmlhttp.open( "POST" , strUrl, true ); xmlhttp.setRequestHeader( "Content-type" , "application/x-www-form-urlencoded" ); xmlhttp.send(strRequestData); } else { xmlhttp.open( "GET" , strUrl+ "?" +strRequestData, true ); xmlhttp.send( null ); } } } |
Anyway, that’s all mostly for my benefit. I usually end up having to write that stupid function from scratch once or twice a month…
You also may ask “why would you bother with the nuts-and-bolts like this when you could use some existing javascript library/framework?”. Well, there are people who use frameworks … and then there are the people who write the frameworks. There’s a lot more job security in the latter :)