| Новости | FAQ | Авторы | Документация | В действии | Библиотека |
| Инструменты | Полезные ссылки | Хостинги | Скачать | Примеры | Форум |
Sanja v.2 09.03.2006 14:41
Ajax Hacks By Bruce Perry<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/2000/REC-xhtml1-20000126/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="js/hacks2_7.js"></script>
<title>Dynamic checkboxes</title>
</head>
<body>
<h3>Voting on Favorite Sports</h3>
<h4>Pick a sports category</h4>
<form action="javascript:void%200">
<table border="0">
<tr><td>
Team Sports:
**<input type="radio" name="_sports" value="team" />**
</td></tr>
<tr><td> Individual Sports:
**<input type="radio" name="_sports" value="individual" />**
</td></tr>
</table>
<hr />
<div id="checks"></div>
</form>
</body>
</html>When the user clicks a checkbox, the page instantly displays either of two different sets of new checkboxes representing either individual sports or team sports. The actual lists of sports that make up the checkboxes are arrays of strings that the server returns. They obviously could be hard-coded into the JavaScript in order to prevent a network hit, but imagine that the checkbox widgets represent values that are frequently changing and/or must be derived from persistent storage on the server, such as complex multiple-choice questions in a questionnaire or product information?var sportType="";
window.onload=function(){
var rads = document.getElementsByTagName("input");
if(rads != null) {
for(var i = 0; i < rads.length; i++) {
if(rads[i].type=="radio"){ rads[i].onclick=function(){
getSports(this)};}
}
}
}
function getSports(obj){
if (obj == null ) { return; }
var url = "";
var val = "";
if(obj.checked) {
val=obj.value;
sportType=val;
url = "http://www.parkerriver.com/s/fav_sports"+
"?sportType="+encodeURIComponent(val)+"&col=y";
httpRequest("GET",url,true);
}
}
//event handler for XMLHttpRequest
function handleResponse(){
try{
if(request.readyState == 4){
if(request.status == 200){
var resp = request.responseText;
if(resp != null){
//return value is a JSON array
var objt = eval(resp);
createChecks(objt);
}
} else {
//request.status is 503
//if the application isn't available;
//500 if the application has a bug
alert(
"A problem occurred with communicating between"+
" the XMLHttpRequest object and the server program.");
}
}//end outer if
} catch (err) {
alert("It does not appear that the server "+
"is available for this application. Please"+
" try again very soon. \nError: "+err.message);
}
}
function createChecks(obj){
var _div = document.getElementById("checks");
var el;
//first remove all existing checkboxes
while(_div.hasChildNodes()){
for(var i = 0; i < _div.childNodes.length; i++){
_div.removeChild(_div.firstChild);
}
}
//obj is an array of new sports names
for(var i=0; i < obj.length;i++) {
el = document.createElement("input");
el.setAttribute("type","checkbox");
el.setAttribute("name",sportType);
el.setAttribute("value",obj[i]);
_div.appendChild(el);
_div.appendChild(document.createTextNode(obj[i]));
_div.appendChild(document.createElement("br"));
}
}
/* httpRequest() and related code omitted for the sake of brevity... */The first stage in generating the checkboxes is to send the request that fetches the values for each of these widgets. When the user clicks a radio button, the code calls getSports(). This function formats a URL based on the value it receives from the checkbox, then sends a request to a server component for a list of related sports./* Initialize a Request object that is already constructed */
function initReq(reqType,url,bool){
try{
/* Specify the function that will handle the
HTTP response */
request.onreadystatechange=handleResponse;
request.open(reqType,url,bool);
request.send(null);
} catch (errv) {
alert(
"The application cannot contact the server "+
"at the moment. "+
"Please try again in a few seconds." );
}
}
/* Wrapper function for constructing a Request object.
Parameters:
reqType: The HTTP request type such as GET or POST.
url: The URL of the server program.
asynch: Whether to send the request asynchronously or not. */
function httpRequest(reqType,url,asynch){
//Mozilla-based browsers
if(window.XMLHttpRequest){
request = new XMLHttpRequest();
initReq(reqType,url,asynch);
} else if (window.ActiveXObject){
request=new ActiveXObject("Msxml2.XMLHTTP");
if (! request){
request=new ActiveXObject("Microsoft.XMLHTTP");
}
if(request){
initReq(reqType,url,asynch);
} else {
alert("Your browser does not permit the use "+
"of all of this application's features!");}
} else {
alert("Your browser does not permit the use "+
"of all of this application's features!");}
}