04-26-2009, 06:34 PM
|
#8 (permalink)
|
|
The Addict
Join Date: Jun 2008
Posts: 335
Thanks: 2
|
Well the reason we learn this is to expedite the process of writing JS, for instance we were to want to send an ajax POST request via jQuery we'd simply do
Code:
$.post('file.php',{postInfo: dataVar}, function(data){ alert('foo'); });
how ever, if we were to do it by hand we'd have something like ( taken from a tutorial, didn't feel like writing it )
Code:
var http_request = false;
function makePOSTRequest(url, parameters) {
http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
// set type accordingly to anticipated content type
//http_request.overrideMimeType('text/xml');
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Cannot create XMLHTTP instance');
return false;
}
http_request.onreadystatechange = alertContents;
http_request.open('POST', url, true);
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Content-length", parameters.length);
http_request.setRequestHeader("Connection", "close");
http_request.send(parameters);
}
function alertContents() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
alert('foo');
} else {
alert('There was a problem with the request.');
}
}
}
postString = 'postData=' + encodeURI(dataVar);
makePOSTRequest('post.php', postString);
You see the advantage? Admittedly though, henceforth the makePOSTRequest function is available for the rest of the script but it is currently not as flexible as the one that jQuery has available
|
|
|
|