第 4 章 XMLHttpRequest 对象 AJAX AJAX 2 iframe AJAX iframe XMLHttpRequest JavaScript iframe AJAX XMLHttpRequest XMLHttpRequest Server Access Object Web XMLHttpRequest
64 第 Ⅱ 部分动态表示 : 用户接口与服务器之间的通信 4.1 Microsoft XMLHttpRequest Internet Explorer IE JavaScript XMLHttpRequest Firefox Safari Opera Microsoft ActiveX JavaScript JavaScript IE7 ActiveX JavaScript IE XMLHttpRequest XMLHttpRequest 2 3 BCO sendrequest URL VCO BCO/VCO BCO VCO 3 12 BCO VCO AJAX (bookmarking) <html> <head> <script> var thecontroller = new Controller();//initialize the controller; var curcmd = null;//used to track the command through the call function init(){ //initialize the page to make sure that the display is blank document.getelementbyid('content').innerhtml=''; function Controller(){//the constructor this.acceptablecommands = {pat:'getpatients', nur:'getnurses'; //the dispatch method is used to handle all requests this.dispatch = function(type, cmd){ //retrieve the current command if the data has arrived if(type == "VCO"){ cmd = curcmd; curcmd = null; else{ curcmd = cmd;//set the current command //see if the command is valid var cmdname = this.acceptablecommands[cmd]; if(cmdname!= null){ var objname = cmdname+type;
第 4 章 XMLHttpRequest 对象 65 //use reflection to instantiate the appropriate control object new window[objname](); //the command objects module function getpatientsbco(){//retrieves the data sendrequest('mainprocedural.php?cmd=pat', window.getpatientsvco); function getpatientsvco(){//updates the page when the data arrives updateview(); function getnursesbco(){//retrieves the data sendrequest('mainprocedural.php?cmd=nur', window.getpatientsvco); function getnursesvco(){//updates the page when the data arrives updateview(); //the request code var http = null;// global variable holding the XMLHttpRequest object to be used in the makecall method as well as in the callback function function sendrequest(url, avco){ //get a request object for all types of browsers. if (!window.xmlhttprequest) { //if we are running IE 6 or older then the XMLHttpRequest method is not defined for the window object. window.xmlhttprequest = function() { return new ActiveXObject("Microsoft.XMLHTTP"); ; try { http = new XMLHttpRequest(); catch(e) { return; //open connection to the HTTP server http.open('get',url, true); //Set the function to be called when the server communicates back to the client. http.onreadystatechange = avco; //Send off the completed request. http.send(null); //a function to modify the content div function updateview(){ //check to see if the response is complete if(http.readystate == 4){ //Check to see if the processing of the request was successful.
66 第 Ⅱ 部分动态表示 : 用户接口与服务器之间的通信 if(http.status == 200){ var data = http.responsetext; document.getelementbyid('content').innerhtml = data; </script> </head> <body onload='init()'> <input type='button' value='patients' onclick='thecontroller.dispatch("bco","pat")' /> <input type='button' value='nurse Information' onclick='thecontroller.dispatch("bco","nur")' /> <div id = 'content' ></div> </body> </html> HTTP sendrequest XMLHttpRequest JavaScript IE IE Web if (!window.xmlhttprequest) { window.xmlhttprequest = function() { return new ActiveXObject("Microsoft.XMLHTTP"); ; if JavaScript XMLHttpRequest XMLHttpRequest XMLHttpRequest IE6 IE XMLHTTP ActiveX sendrequest if-then-else CPU XMLHttpRequest XMLHttpRequest http.open('get',url, true); open GET POST HTTP URL Nurse Information 4-1
第 4 章 XMLHttpRequest 对象 67 4-1 XMLHttpRequest URL URL / getnrusesbco main/php?cmd=nur' URL URL Web Web XMLHttpRequest 7 open true XMLHttpRequest Web onreadystatechange readystatechange JavaScript 4-1 XMLHttpRequest 4-2 readystate VCO sendrequest BCO http.onreadystatechange = avco;
68 第 Ⅱ 部分动态表示 : 用户接口与服务器之间的通信 4-1 XMLHttpRequest open() setrequestheader() send() abort() getallresponseheaders() getresponseheader() HTTP GET POST HTTP URL URL Web open(type,url,async,username,passwork) / HTTP HTTP setrequestheader(key,value) URL DOM null send(somedata) abort() abort() / getresponseheader(key) 4-2 XMLHttpRequest onreadystatechange readystate status responsexml 5 0 1 2 3 4 0 2 3 4 HTTP 404 200 XML DOM XML null
第 4 章 XMLHttpRequest 对象 69 ( ) responsetext statustext status 2 4.2 Server Access Object Server Access Object ( ) XMLHttpRequest BCO VCO ( 3 ) Server Access Object ServerAO JavaScript ServerAO Data Access Object(DAO ) DAO ServerAO Server Access Object VCO VCO notify ( null) VCO BCO ServerAO public static URL PHP (main.php) iframe main.html www.oraclepress.com <html> <head> <script src="serveraccess.js"></script> <script src="co.js"></script> <script src="cntrl.js"></script> </head> <body onload='init()'> <input type='button'value='patient Information' onclick='thecontroller.dispatch("pat")'/> <input type='button'value='nurse Information' onclick='thecontroller.dispatch("nur")'/> <div id ='content'></div> </body> </html> cntrl.js var thecontroller =new Controller();//initialize the controller;
70 第 Ⅱ 部分动态表示 : 用户接口与服务器之间的通信 function init(){ //initialize the page to make sure that the display is blank document.getelementbyid('content').innerhtml=''; function Controller(){//the constructor //a map of approved commands this.acceptablecommands ={pat:'getpatients',nur:'getnurses'; //the dispatch method is used to handle all requests this.dispatch =function(cmd){ //see if the command is valid var cmdname =this.acceptablecommands [cmd ]; if(cmdname!=null){ var objname =cmdname+'bco'; //use reflection to instantiate the appropriate control object new window [objname ](); CO.js var thesao =new ServerAO('main.php');//the server access object for all communication *Patient information function getpatientsbco(){//retrieves the data //data and headers are not included as parameters.they will be null. thesao.makecall('get',new getpatientsvco(),'text',true,'cmd=pat'); function getpatientsvco(){//updates the page when the data arrives this.notify =function(data){ document.getelementbyid('content').innerhtml =data; *Nurse information function getnursesbco(){ thesao.makecall('get',new getnursesvco(),'text',true,'cmd=nur'); function getnursesvco(){//updates the page when the data arrives this.notify =function(data){ document.getelementbyid('content').innerhtml =data; ServerAccess.js www.oraclepress.com *A representation of the uninitialized request state '0'.
第 4 章 XMLHttpRequest 对象 71 ServerAO.UNITITIALIZED =0; *A representation of the setup but not sent request state '1'. ServerAO.SETUP =1; *A representation of the sent but not having received request state '2'. ServerAO.SENT =2; *A representation of the in process request state '3'. ServerAO.IN_PROCESS =3; *A representation of the complete request state '4'. ServerAO.COMPLETE =4; *A representation of the HTTP status code for file retrieval on FirefFox '0'.For other HTTP status codes go to www.w3.org/protocols/rfc2616/rfc2616-sec10.html. ServerAO.FireFox_HTTP_File_Access =0; *A representation of the HTTP status code for file retrieval on OSX 'undefined'. For other HTTP status codes go to www.w3.org/protocols/rfc2616/rfc2616-sec10.html. ServerAO.OSX_HTTP_File_Access =null; *A representation of the HTTP status code for OK '200'.For other HTTP status codes go to www.w3.org/protocols/rfc2616/rfc2616-sec10.html. ServerAO.HTTP_OK =200; *A representation of the HTTP status code for Bad Request '400'.For other HTTP status codes go to www.w3.org/protocols/rfc2616/rfc2616-sec10.html. ServerAO.HTTP_BADREQUEST =400; *A representation of the HTTP status code for Version Not Supported '505'.For other HTTP status codes go to www.w3.org/protocols/rfc2616/rfc2616-sec10.html. ServerAO.HTTP_VERSION_NOT_SUPPORTED =505;
72 第 Ⅱ 部分动态表示 : 用户接口与服务器之间的通信 *Constructor for a new ServerAO instance.the purpose of the Server Access Object is to *create all requests for data from the server as well as requests for posting of data *to the server and make all preparations required to successfully make *these calls.all calls made are asynchronous. *parameter 1:URL -the URL of the main access point for the application function ServerAO(URL){ this.url =URL; *Executes the call to the server to post or get data.creation and use of an xmlhttprequestobject happens within this method. *parameter 1:{StringcallType -GET,POST,or other HTTP type *parameter 2:{ObjectwhenDone -the ViewControlObject to activate when data returns from the server. *parameter 3:{StringdataType -values are either Text or XML *parameter 4:{booleanrefresh -a indicating if refreshing should be enforced even if the data is currently cached. *parameter 5:{StringparameterSequence -the parameter list to be added to the URL *parameter 6:{String or DOM elementdata -any data to be sent with a POST type request *parameter 7:{ObjectHTTPHeaders -a map of headers and values this.makecall =function(calltype,whendone,datatype,refresh,parametersequence, data,httpheaders){ if(datatype ==null){ datatype ='Text'; if(refresh ==null){ refresh =false; * get a request object for all types of browsers. if (!window.xmlhttprequest){ * if we are running IE 6 or older then the XMLHttpRequest method is * not defined.if we define it the first time it is used as being * the microsoft ActiveX method of retrieving a request object then * it will be used each time a new call is made and not need to be * defined over again. window.xmlhttprequest =function(){ return new ActiveXObject("Microsoft.XMLHTTP"); ; var http =null;
第 4 章 XMLHttpRequest 对象 73 try { http =new XMLHttpRequest(); catch(e){ return; var isasynch =true;//enforce always asynchronous * open a connection to the server located at 'this.url'. http.open(calltype,this.url+'?'+parametersequence,isasynch); if(refresh){ * if we are to disable caching and force a call to the server then the 'If-Modified-Since'header will * need to be set to some time in the past. http.setrequestheader("if-modified-since","sat,1 Jan 2000 00:00:00 GMT"); //if there are headers then add them to the request if(httpheaders!=null){ for(var key in HTTPHeaders){ http.setrequestheader(key,httpheaders [key ]); //if a POST is being done and data is to be sent,set the content type header so that the data will be encoded correctly and sent on to the server for decoding if(calltype =="POST"&&data!=null){ http.setrequestheader('content-type','application/x-www-form-urlencoded; charset=utf-8'); * Set the function to be called when the server communicates with the client. * For the ServerAO this is an inline function that is the callback function defined below. * The reason for the inline function is so that variables from within the makecall method can be used.if a non-inline * function is used then only the name of the function to be called is set as the onreadystatechange * method of the http class. http.onreadystatechange =function(){ * Only handle completed,finished messages from the server if(http.readystate ==ServerAO.COMPLETE){ *Retrieve the data if the server returns that the processing of the request was successful or if *the request was directly for a file on the server disk.
74 第 Ⅱ 部分动态表示 : 用户接口与服务器之间的通信 var resultdata =null;//null represents an error in client side processing var errorheader =http.getresponseheader('custom-error-header'); //Firefox sets errorheader equal to null //IE7 sets it equal to an empty string if(errorheader!=null &&errorheader.length >0){ //whendone can not be reset so return early new ErrorHandlerVCO().notify(errorHeader); http =null; return; else if(http.status ==ServerAO.HTTP_OK http.status ==ServerAO.FireFox_HTTP_File_Access http.status ==ServerAO.OSX_HTTP_File_Access){ resultdata =http ['response'+datatype ];//get the data as either Text or XML if(whendone!=null){ //call notify for the whendone VCO object whendone.notify(resultdata); http =null;//force a release of the memory for the request object ; *Send off the completed request and include any data for a 'POST'request. http.send(data); BCO VCO SAO BCO SAO makecall VCO notify onreadystatechange VCO notify VCO notify VCO makecall Server Access Object BCO HTTP IE ( ) HTTP If-Modified-Since http.setrequestheader("if-modified-since","sat,1 Jan 2000 00:00:00 GMT");
第 4 章 XMLHttpRequest 对象 75 HTTP HTTPHeaders 7 / HTTP if(httpheaders!=null){ for(var key in HTTPHeaders){ http.setrequestheader(key,httpheaders [key ]); for XMLHttpRequest onreadystatechange VCO ServerAO SAO VCO VCO notify null VCO Controller dispatch dispatch BCO VCO dispatch BCO this.dispatch =function(cmd){ //see if the command is valid var cmdname =this.acceptablecommands [cmd ]; if(cmdname!=null){ var objname =cmdname+'bco'; //use reflection to instantiate the appropriate control object new window [objname ](); ServerAO VCO notify dispatch type onclick BCO VCO 4.3 XMLHttpRequest HTML HTML 3 iframe
76 第 Ⅱ 部分动态表示 : 用户接口与服务器之间的通信 XMLHttpRequest BCO VCO 3 BCO / BCO VCO AJAX