DoubleEO 发表于 2013-1-23 02:55:59

javascript的一些总结(8)

16.通用的ajax库
var ajaxreq=false, ajaxCallback;// ajaxRequest: Sets up a requestfunction 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 functionfunction 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 filefunction getQuestions() {   obj=document.getElementById("question");   obj.firstChild.nodeValue="(please wait)";   ajaxCallback = nextQuestion;   ajaxRequest("questions.xml");}// display the next questionfunction nextQuestion() {   questions = ajaxreq.responseXML.getElementsByTagName("q");   obj=document.getElementById("question");   if (qn < questions.length) {      q = questions.firstChild.nodeValue;      obj.firstChild.nodeValue=q;   } else {      obj.firstChild.nodeValue="(no more questions)";   }}// check the user's answerfunction checkAnswer() {   answers = ajaxreq.responseXML.getElementsByTagName("a");   a = answers.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 buttonsobj=document.getElementById("startq");obj.onclick=getQuestions;ans=document.getElementById("submit");ans.onclick=checkAnswer;
页: [1]
查看完整版本: javascript的一些总结(8)