AJAX - The Complete Reference

(avery) #1

78 Part I: Core Ideas


The complete example is now shown. It also can be found online at http://ajaxref.com/
ch3/asyncsend.html.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Chapter 3 : XMLHttpRequest - Asynchronous Send</title>
<link rel="stylesheet" href="http://ajaxref.com/ch3/global.css"
type="text/css" media="screen" />
<script type="text/javascript">
function createXHR()
{
try { return new XMLHttpRequest(); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
return null;
}

function sendRequest()
{
var xhr = createXHR();
if (xhr)
{
xhr.open("GET", "http://ajaxref.com/ch3/helloworld.php", true);
xhr.onreadystatechange = function(){handleResponse(xhr);};
xhr.send(null);
}
}
function handleResponse(xhr)
{
if (xhr.readyState == 4 && xhr.status == 200)
{
var responseOutput = document.getElementById("responseOutput");
responseOutput.innerHTML = "<h3>reponseText</h3>" + xhr.responseText;
responseOutput.style.display = "";
}
}
window.onload = function ()
{
document.requestForm.requestButton.onclick = function () { sendRequest(); };
};
</script>
</head>
<body>

<form action="#" name="requestForm">
<input type="button" name="requestButton"
value="Send an Asynchronous Request" />
</form>
Free download pdf