[b]16.通用的ajax库[/b]
ajax的小例子
var ajaxreq=false, ajaxCallback;
// ajaxRequest: Sets up a request
function ajaxRequest(filename) {
try {
// Firefox / IE7 / Others
ajaxreq= new XMLHttpRequest();
} catch (error) {
try {
// IE 5 / IE 6
ajaxreq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (error) {
return false;
}
}
ajaxreq.open("GET",filename);
ajaxreq.onreadystatechange = ajaxResponse;
ajaxreq.send(null);
}
// ajaxResponse: Waits for response and calls a function
function ajaxResponse() {
if (ajaxreq.readyState !=4) return;
if (ajaxreq.status==200) {
// if the request succeeded...
if (ajaxCallback) ajaxCallback();
} else alert("Request failed: " + ajaxreq.statusText);
return true;
}
ajax的小例子
<html>
<head><title>Ajax Test</title>
<script language="JavaScript" type="text/javascript"
src="ajax.js">
</script>
</head>
<body>
<h1>Ajax Quiz Example</h1>
<form>
<p><b>Question:</b>
<span id="question">...
</span>
</p>
<p><b>Answer:</b>
<input type="text" name="answer" id="answer">
<input type="button" value="Submit" id="submit">
</p>
<input type="button" value="Start the Quiz" id="startq">
</form>
<script language="JavaScript" type="text/javascript"
src="quiz.js">
</script>
</body>
</html>
<?xml version="1.0" ?>
<questions>
<q>What DOM object contains URL information for the window?</q>
<a>location</a>
<q>Which method of the document object finds the object for an element?</q>
<a>getElementById</a>
<q>If you declare a variable outside a function, is it global or local?</q>
<a>global</a>
<q>What is the formal standard for the JavaScript language called?</q>
<a>ECMAScript</a>
</questions>
var qn=0;
// load the questions from the XML file
function getQuestions() {
obj=document.getElementById("question");
obj.firstChild.nodeValue="(please wait)";
ajaxCallback = nextQuestion;
ajaxRequest("questions.xml");
}
// display the next question
function nextQuestion() {
questions = ajaxreq.responseXML.getElementsByTagName("q");
obj=document.getElementById("question");
if (qn < questions.length) {
q = questions[qn].firstChild.nodeValue;
obj.firstChild.nodeValue=q;
} else {
obj.firstChild.nodeValue="(no more questions)";
}
}
// check the user's answer
function checkAnswer() {
answers = ajaxreq.responseXML.getElementsByTagName("a");
a = answers[qn].firstChild.nodeValue;
answerfield = document.getElementById("answer");
if (a == answerfield.value) {
alert("Correct!");
}
else {
alert("Incorrect. The correct answer is: " + a);
}
qn = qn + 1;
answerfield.value="";
nextQuestion();
}
// Set up the event handlers for the buttons
obj=document.getElementById("startq");
obj.onclick=getQuestions;
ans=document.getElementById("submit");
ans.onclick=checkAnswer;