01chapter world wide wait
Ajax Ajax Asynchronous JavaScript and XML Ajax Ajax XMLHttpRequest API HTTP connect Ajax 6 1 32 0 7 6 Ajax asynchronous XML extensible Markup Language Language XMLHttpRequest XML HTML CSS Cascading Style Sheets HTML CSS DOM Document Object Model DOM XML HTML DOM XSLT extensible Stylesheet Language and Transformation XML XMLHttpquest XMLHttpquest 24
Ajax 5 0 HTTP XMLHTTP IE 67 Ajax Web 2 0 Ajax Rich Internet Application RIA Zimbra Rollyohttpwww rollyo com httpmap search ch index en html Web 2 0 Ajax httpen wiki pedia org wiki List of websites using Ajax Ajax Ajax URL Ajax RSH Ajax Form select textarea text Ajax XMLHttpRequest 25
API API XMLHttpRequest property IE 5 0 1 32 0 7 7 6 onreadystatechange : readystate readystate : uninitialized open loading send loaded send header status interactive reponsetext completed responsetext : XMLHttpRequest onloadonprogressonerror addeventlistenerdispatcheventoverridemimetyperemoveeventlistenner httpwww xulplanet com references objref XMLHttpRequest html 26
responsexml : DOM XML status : 200 Okay404 Not Found statustext : HTTP abort() : void HTTP getallresponseheaders() : HTTP getresponseheader(string header) : open(string method,string url,boolean asynch) : void HTTP send(string) : void HTTP setrequestheader(string header,string value) : void open HACK #1 Ajax 27
HTTP Ajax XMLHttpRequest IE IE 5 0 IE Microsoft XMLHTTP Msxml2 XMLHTTP ActiveX IE request object Ajax ActiveX HTTP 7 1 1 5 28
Window window XMLHttpRequest if(window.xmlhttprequest){ request = new XMLHttpRequest(); request.onreadystatechange=handleresponse; request.open("get",theurl,true); request.send(null); request XMLHttpRequest if widows XMLHttpRequest XMLHttpRequest null undefined true new onreadystatechange handleresponse XMLHttpRequest opensend 29
windows XMLHttpRequest else if (window.activexobject){ request=new ActiveXObject("Microsoft.XMLHTTP"); if (! request){ request=new ActiveXObject("Msxml2.XMLHTTP"); if(request){ request.onreadystatechange=handleresponse; request.open(reqtype,url,true); request.send(null); window ActiveXObject program ID Microsoft XMLHTTP Msxml2 XMLHTTP IE Msxml2 XMLHTTP 4 0 MSXML if request request null undefined Ajax /* : reqtype: HTTP. GET POST url: URL asynch: */ function httprequest(reqtype,url,asynch){ // if(window.xmlhttprequest){ 30
request = new XMLHttpRequest(); else if (window.activexobject){ request=new ActiveXObject("Msxml2.XMLHTTP"); if (! request){ request=new ActiveXObject("Microsoft.XMLHTTP"); // ActiveXObject request null if(request){ initreq(reqtype,url,asynch); else { alert( "Your browser does not permit the use of all "+ "of this application's features!"); /* */ function initreq(reqtype,url,bool){ /* HTTP */ request.onreadystatechange=handleresponse; request.open(reqtype,url,bool); request.send(null); POST XMLHttpRequest POST HACK #2 POST HTTP Ajax POST 31
POST POST POST 1 1 HTML <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/tr/1999/rec-html401-19991224/strict.dtd"> <html> <head> <script type="text/javascript" src="/parkerriver/js/hack2.js"></script> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>send a data tidbit</title> </head> <body> <h3>a Few Facts About Yourself...</h3> <form action="javascript:void%200" onsubmit="senddata();return false"> 32
<p>first name:<input type="text" name="firstname" size="20"> </p> <p>last name:<input type="text" name="lastname" size="20"> </p> <p>gender:<input type="text" name="gender" size="2"> </p> <p>country of origin:<input type="text" name="country" size="20"> </p> <p><button type="submit">send Data</button></p> </form> </body> </html> hack2 js onsubmit sentdata POST setquerystring text textarea hack2 js setquerystring function setquerystring(){ querystring=" "; var frm = document.forms[0]; var numberelements = frm.elements.length; for(var i = 0; i < numberelements; i++) { if(i < numberelements-1) { querystring += frm.elements[i].name+"="+ 33
encodeuricomponent(frm.elements[i].value)+"&"; else { querystring += frm.elements[i].name+"="+ encodeuricomponent(frm.elements[i].value); POST firstname=bruce&lastname=perry&gender=m&country=usa POST HTTP HTTP onsubmit senddata var request; var querystring; // POST function senddata(){ setquerystring(); var url="http://www.parkerriver.com/s/sender"; httprequest("post",url,true); /* : reqtype: HTTP. GET POST url: URL isasynch: */ function initreq(reqtype,url,isasynch){ /* HTTP */ request.onreadystatechange=handleresponse; request.open(reqtype,url,isasynch); /* POST Content-Type */ request.setrequestheader("content-type", "application/x-www-form-urlencoded; charset=utf-8"); request.send(querystring); 34
/* Parameters: reqtype: HTTP. GET POST url: URL asynch: */ function httprequest(reqtype,url,asynch){ // if(window.xmlhttprequest){ request = new XMLHttpRequest(); else if (window.activexobject){ request=new ActiveXObject("Msxml2.XMLHTTP"); if (! request){ request=new ActiveXObject("Microsoft.XMLHTTP"); // ActiveXObject request null if(request){ initreq(reqtype,url,asynch); else { alert("your browser does not permit the use of all "+ alert("of this application's features!"); httprequest initreq request onreadystatechange handleresponse open open POST Content Type 35
POST request.setrequestheader("content-type", "application/x-www-form-urlencoded; charset=utf-8"); request.send(querystring); querystring send("firstname=bruce&lastname=perry&gender=m&country=usa"); handleresponse initreq request.onreadystatechange=handleresponse; readystate 4 HTTP 200 200 HTTP responstext //XMLHttpRequest function handleresponse(){ 36
if(request.readystate == 4){ if(request.status == 200){ alert(request.responsetext); else { alert("a problem occurred with communicating between "+ alert("the XMLHttpRequest object and the server program."); // if 1 2 POST XML POST param protected void dopost(httpservletrequest httpservletrequest, HttpServletResponse httpservletresponse) throws ServletException, IOException { Map reqmap = httpservletrequest.getparametermap(); String val=null; String tag = null; StringBuffer body = new StringBuffer("<params>\n"); boolean wellformed = true; Map.Entry me = null; for(iterator iter= reqmap.entryset().iterator();iter.hasnext();) { me=(map.entry) iter.next(); 37
val= ((String[])me.getValue())[0]; tag = (String) me.getkey(); if (! XMLUtils.isWellFormedXMLName(tag)){ wellformed=false; break; body.append("<").append(tag).append(">"). append(xmlutils.escapebodyvalue(val)). append("</").append(tag).append(">\n"); if(wellformed) { body.append("</params>"); sendxml(httpservletresponse,body.tostring()); else { sendxml(httpservletresponse,"<notwellformedparams />"); Jakarta Commons Betwixt XMLUtils XML POST name name XML HACK #3 Ajax XMLHttpRequest http request js XML 38
HttpRequest <script type="text/javascript" src="js/http_request.js"></script> http request js var request = null; /* : reqtype: HTTP GET POST url: URL asynch: resphandle: (arguments[4]) POST */ function httprequest(reqtype,url,asynch,resphandle){ // if(window.xmlhttprequest){ request = new XMLHttpRequest(); else if (window.activexobject){ request=new ActiveXObject("Msxml2.XMLHTTP"); if (! request){ request=new ActiveXObject("Microsoft.XMLHTTP"); // if(request) { //reqtypepost 5 if(reqtype.tolowercase()!= "post") { initreq(reqtype,url,asynch,resphandle); else { //POST var args = arguments[4]; if(args!= null && args.length > 0){ initreq(reqtype,url,asynch,resphandle,args); else { alert("your browser does not permit the use of all "+ alert("of this application's features!"); 39
/* */ function initreq(reqtype,url,bool,resphandle){ try{ /* HTTP */ request.onreadystatechange=resphandle; request.open(reqtype,url,bool); //reqtypepost 5 if(reqtype.tolowercase() == "post") { request.setrequestheader("content-type", "application/x-www-form-urlencoded; charset=utf-8"); request.send(arguments[4]); else { request.send(null); catch (errv) { alert( "The application cannot contact "+ "the server at the moment.\n"+ "Please try again in a few seconds.\n"+ "Error detail"+errv.message); 4 5 httprequest var _url = "http://www.parkerriver.com/s/sender"; var _data="first=bruce&last=perry&middle=w"; httprequest("post",_url,true,handleresponse,_data); POST 40
POST 4 http request js HTTP var _url = "http://www.parkerriver.com/s/sender"; // httprequest("post",_url,true,function(){alert(request.responsetext);); httprequest XMLHttpRequest initreq onreadystatechange open send HTTP try catch URL open try catch http request js request function handleresponse(){ var request = null; try{ if(request.readystate == 4){ if(request.status == 200){... 41
HACK #4 XML XML XML GPS Global Positioning System GPS USB GPS XMLXML GPS XML XML metaxml XML xml version1 0 encodingutf 8 0 <?xml version="1.0" encoding="utf-8"?> <gps> <gpsmaker>garmin</gpsmaker> <gpsdevice> Forerunner 301 </gpsdevice> </gps> gps gpsmaker gpsdevice Ajax XML XML Web Service HTTP responsexml Ajax DOM 42
function handleresponse(){ if(request.readystate == 4){ if(request.status == 200){ var doc = request.responsexml;... doc DOM API XML XML DOM HTML POST XML div HTML <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/tr/1999/rec-html401-19991224/strict.dtd"> <html> <head> <script type="text/javascript" src="js/hack3.js"></script> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>receive XML response</title> </head> <body> <h3>a Few Facts About Yourself...</h3> <form action="javascript:void%200" onsubmit="senddata();return false"> <p>first name: <input type="text" name="firstname" size="20"> </p> <p>last name: <input type="text" name="lastname" size="20"> </p> <p>gender: <input type="text" name="gender" size="2"> </p> <p>country of origin: <input type="text" name="country" size="20"> </p> 43
<p><button type="submit">send Data</button></p> <div id="docdisplay"></div> </form> </body> </html> 1 3 hack3 js POST XML paramsfirstname Brucefirstname params POST Ajax XML var request; var querystring; //POST function senddata(){ 44
setquerystring(); var url="http://www.parkerriver.com/s/sender"; httprequest("post",url,true); //XMLHttpRequest function handleresponse(){ if(request.readystate == 4){ if(request.status == 200){ var doc = request.responsexml; var info = getdocinfo(doc); stylizediv(info,document.getelementbyid(""docdisplay"")); else { alert( ""A problem occurred with communicating between ""+ alert( ""the XMLHttpRequest object and the server program.""); // if /* */ function initreq(reqtype,url,bool){ /*HTTP */ request.onreadystatechange=handleresponse; request.open(reqtype,url,bool); request.setrequestheader(""content-type"", ""application/x-www-form-urlencoded; charset=utf-8""); /* */ //request.overridemimetype(""text/xml""); request.send(querystring); /* : reqtype:http GET POST url: URL asynch: */ function httprequest(reqtype,url,asynch){ // Hack #1 function setquerystring(){ querystring=""; var frm = document.forms[0]; 45
var numberelements = frm.elements.length; for(var i = 0; i < numberelements; i++) { if(i < numberelements-1) { querystring += frm.elements[i].name+"="+ encodeuricomponent(frm.elements[i].value)+"&"; else { querystring += frm.elements[i].name+"="+ encodeuricomponent(frm.elements[i].value); /* div. */ function stylizediv(bdytxt,div){ //DIV div.innerhtml=""; div.style.backgroundcolor="yellow"; div.innerhtml=bdytxt; /*DOM Document XML document */ function getdocinfo(doc){ var root = doc.documentelement; var info = "<h3>document root element name: <h3 />"+ root.nodename; var nds; if(root.haschildnodes()) { nds=root.childnodes; info+= "<h4>root node's child node names/values:<h4/>"; for (var i = 0; i < nds.length; i++){ info+= nds[i].nodename; if(nds[i].haschildnodes()){ info+= " : \"+nds[i].firstchild.nodevalue+"\"<br />"; else { info+= " : Empty<br />"; return info; 46
POST getdocinfo XML var doc = request.responsexml; var info = getdocinfo(doc); getdocinfo XML var root doc documentelement stylizediv sytlizediv HTML div function stylizediv(bdytxt,div){ //div div.innerhtml=""; div.style.backgroundcolor="yellow"; div.innerhtml=bdytxt; 47
DOM API XML HACK #5 XML request responsetext 48
HTML hack9 js <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/tr/1999/rec-html401-19991224/strict.dtd"> <html> <head> <script type="text/javascript" src="js/hack9.js"></script> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>choose a stock</title> </head> <body> <h3>stock prices</h3> <form action="javascript:void%200" onsubmit= "getstockprice(this.stsymbol.value);return false"> <p>enter stock symbol: <input type="text" name= "stsymbol" size="4"><span id="stprice"></span></p> <p><button type="submit">get Stock Price</button></p> </form> </body> 1 5 GRMN span getstockprice stsymbol 49
var request; var symbol; // function getstockprice(sym){ symbol=sym; if(sym){ var url="http://localhost:8080/parkerriver/s/stocks?symbol="+sym; httprequest("get",url,true); // XMLHttpRequest function handleresponse(){ if(request.readystate == 4){ if(request.status == 200){ /* */ var stockprice = request.responsetext; var info = "«The price is: $"+stockprice+"»"; document.getelementbyid("stprice").style.fontsize="0.9em"; document.getelementbyid("stprice").style. backgroundcolor="yellow"; document.getelementbyid("stprice").innerhtml=info; else { alert("a problem occurred with communicating between "+ alert("the XMLHttpRequest object and the server program."); // if 50
/* httprequest() Hack #1 */ getstockprice httprequest handle Res ponse request readystate4 HTTP 200 request responsetext DOM CSS document.getelementbyid("stprice").style.fontsize="0.9em"; document.getelementbyid("stprice").style.backgroundcolor="yellow"; document.getelementbyid("stprice").innerhtml =info; span innerhtml HACK #6 51
Ajax undefined 1 6 HTML <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/tr/1999/rec-html401-19991224/strict.dtd"> <html> <head> <script type="text/javascript" src="/parkerriver/js/hack4.js"> </script> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>tally your stocks</title> </head> <body> <h3>your total Stock Holdings</h3> 52
<form action="javascript:void%200" onsubmit= "getstockprice(this.stsymbol.value,this.numshares.value);return false"> <p>enter stock symbol: <input type="text" name="stsymbol" size="4"> <span id="stprice"></span></p> <p>enter share amount:<input type="text" name="numshares" size="10"></p> <p><button type="submit">get Total Value</button></p> <div id="msgdisplay"></div> </form> </body> </html> Get Total Value onsubmit getstockprice false submit HTML hack4 js var request; var symbol; // var numberofshares; function getstockprice(sym,shs){ if(sym && shs){ symbol=sym; numberofshares=shs; var url="http://localhost:8080/parkerriver/s/stocks?symbol="+sym; httprequest("get",url,true); //XMLHttpRequest function handleresponse(){ if(request.readystate == 4){ alert(request.status); if(request.status == 200){. var stockprice = request.responsetext; 53
try{ if(isnan(stockprice)) { throw new Error( "The returned price is an invalid number."); if(isnan(numberofshares)) { throw new Error( "The share amount is an invalid number."); var info = "Total stock value:"+ calctotal(stockprice); displaymsg(document. getelementbyid("msgdisplay"),info,"black"); document.getelementbyid("stprice").style.fontsize="0.9em"; document.getelementbyid("stprice").innerhtml ="price: "+stockprice; catch (err) { displaymsg(document.getelementbyid("msgdisplay"), "An error occurred: "+ err.message,"red"); else { alert( "A problem occurred with communicating between the "+ "XMLHttpRequest object and the server program."); // if /* httprequest() initreq() Hack #1 #2.. */ function calctotal(price){ return stripextranumbers(numberofshares * price); /* 4 */ function stripextranumbers(num){ // var n2 = num.tostring(); if(n2.indexof(".") == -1) { return num; // 4 parsefloat if(typeof num == "string"){ num = parsefloat(num).tofixed(4); else { num = num.tofixed(4); 54
// 0 return parsefloat(num.tostring().replace(/0*$/,"")); function displaymsg(div,bdytext,txtcolor){ //DIV div.innerhtml=""; div.style.backgroundcolor="yellow"; div.style.color=txtcolor; div.innerhtml=bdytext; handleresponse var stockprice request responsetext stockprice API isnan Not a Number stockprice goodbye isnangoodbye true true calctotal stripextranumbers 55
DOM Document Object Model handleresponse displaymsg id stprice div innerhtml displaymsg(document.getelementbyid("msgdisplay"),info,"black"); document.getelementbyid("stprice").style.fontsize="0.9em"; document.getelementbyid("stprice").innerhtml ="price: "+stockprice; displaymsg function displaymsg(div,bdytext,txtcolor){ //DIV div.innerhtml=""; div.style.backgroundcolor="yellow"; div.style.color=txtcolor; div.innerhtml=bdytext; 1 7 56
1 8 HACK #7 Ajax JSON JavaScript Object Notation JSON 57
JSON JSON JSON JSON hello 1 2 3 4 truefalsenull JSON POST JSON { firstname:"bruce", lastname:"perry", gender:"m", country:"usa" 58
POST HTML Ajax JSON div JSON HTML <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/tr/1999/rec-html401-19991224/strict.dtd"> <html> <head> <script type="text/javascript" src="js/hack5.js"></script> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>receive JSON response</title> </head> <body> <h3>a Few Facts About Yourself...</h3> <form action="javascript:void%200" onsubmit="senddata();return false"> <p>first name:<input type="text" name="firstname" size="20"> </p> <p>last name: <input type="text" name="lastname" size="20"> </p> <p>gender:<input type="text" name="gender" size="2"> </p> <p>country of origin:<input type="text" name="country" size="20"> </p> <p><button type="submit">send Data</button></p> <div id="json"></div> <div id="props"></div> </form> </body> </html> 1 9 59
hack5 js POST var request; var querystring; //POST 60
function senddata(){ setquerystring(); url="http://localhost:8080/parkerriver/s/json"; httprequest("post",url,true); // XMLHttpRequest function handlejson(){ if(request.readystate == 4){ if(request.status == 200){ var resp = request.responsetext; var func = new Function("return "+resp); var objt = func(); var div = document.getelementbyid("json"); stylizediv(resp,div); div = document.getelementbyid("props"); div.innerhtml="<h4>in object form...</h4>"+ div.innerhtml="<h5>properties</h5>firstname= "+ div.innerhtml=objt.firstname +"<br />lastname="+ div.innerhtml=objt.lastname+ "<br />gender="+ div.innerhtml=objt.gender+ "<br />country="+ div.innerhtml=objt.country; else { alert("a problem occurred with communicating between "+ alert("the XMLHttpRequest object and the server program."); // if /* */ function initreq(reqtype,url,bool){ /* HTTP */ request.onreadystatechange=handlejson; request.open(reqtype,url,bool); request.setrequestheader("content-type", "application/x-www-form-urlencoded; charset=utf-8"); request.send(querystring); /* : reqtype: HTTP. GET POST 61
url: URL asynch: */ function httprequest(reqtype,url,asynch){ // Hack #1, #2 function setquerystring(){ querystring=""; var frm = document.forms[0]; var numberelements = frm.elements.length; for(var i = 0; i < numberelements; i++){ if(i < numberelements-1){ querystring += frm.elements[i].name+"="+ encodeuricomponent(frm.elements[i].value)+"&"; else { querystring += frm.elements[i].name+"="+ encodeuricomponent(frm.elements[i].value); function stylizediv(bdytxt,div){ //DIV div.innerhtml=" "; div.style.fontsize="1.2em"; div.style.backgroundcolor="yellow"; div.appendchild(document.createtextnode(bdytxt)); initreq HTTP handlejson XML JSON HTTP JSON 62
handlejson resp HTTP request responsetext Functio var func = new Function("return"+resp); func Function var resp = request.responsetext; var obj = eval( "(" + resp + ")" ); var resp = request.responsetext; // resp "[1,2,3,4]" var arrobject = eval(resp); DOM 63
serialization var objt = func(); var div = document.getelementbyid("json"); stylizediv(resp,div); div = document.getelementbyid("props"); div.innerhtml="<h4>in object form...</h4><h5>properties</h5> firstname= "+ objt.firstname +"<br />lastname="+ objt.lastname+ "<br />gender="+ objt.gender+ "<br />country="+ objt.country; objt objt firstname 1 10 64
Java dopost protected void dopost(httpservletrequest httpservletrequest, HttpServletResponse httpservletresponse) throws ServletException, IOException { Map valmap = httpservletrequest.getparametermap(); StringBuffer body = new StringBuffer("{\n"); if(valmap!= null) { String val=null; String key = null; Map.Entry me = null; Set entries = valmap.entryset(); int size = entries.size(); int counter=0; for(iterator iter= entries.iterator();iter.hasnext();) { counter++; me=(map.entry) iter.next(); val= ((String[])me.getValue())[0]; key = (String) me.getkey(); if(counter < size) { body.append(key).append(":\"").append(val).append("\",\n"); else { //remove comma for last entry body.append(key).append(":\"").append(val).append("\"\n"); body.append(""); AjaxUtil.sendText(httpServletResponse,body.toString()); AjaxUtil Content Type text plaincharset UTF 8 HTTP JSONContetn Type application x json 65
AjaxUtil response.setheader("cache-control", "no-cache"); HACK #8 Ajax backend Ajax URL open 66
hack6 js HTML <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/tr/1999/rec-html401-19991224/strict.dtd"> <html> <head> <script type="text/javascript" src="js/hack6.js"></script> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>tally your stocks</title> </head> <body> <h3>your total Stock Holdings</h3> <form action="javascript:void%200" onsubmit= "getstockprice(this.stsymbol.value,this.numshares.value);return false"> <p>enter stock symbol: <input type="text" name="stsymbol" size="4"> <span id="stprice"></span></p> <p>enter share amount:<input type="text" name="numshares" size="10"> </p> <p><button type="submit">get Total Value</p> <div id="msgdisplay"></div> </form> </body> </html> 1 11 URL handelresponse request onreadystatechange handle Response try catch finally 67
function handleresponse(){ var statusmsg=""; try{ if(request.readystate == 4){ if(request.status == 200){ /* */ var stockprice = request.responsetext; try{ if(isnan(stockprice)) { throw new Error( "The returned price is an invalid number."); if(isnan(numberofshares)) { throw new Error( "The share amount is an invalid number."); var info = "Total stock value: "+ calctotal(stockprice); displaymsg(document. getelementbyid("msgdisplay"),info,"black"); document.getelementbyid("stprice").style.fontsize="0. 9em"; document.getelementbyid("stprice").innerhtml ="price: "+ stockprice; catch (err) { displaymsg(document.getelementbyid("msgdisplay"), "An error occurred: "+ err.message,"red"); 68
else { // request.status 503 // 500 alert( "A problem occurred with communicating between the " "XMLHttpRequest object and the server program. "+ "Please try again very soon"); // if catch (err) { alert("it does not appear that the server "+ alert("is available for this application. Please "+ alert("try again very soon.\nerror: "+err.message); try catch try status request status catch 1 12 69
try catch finally request status 503Service Unavailable status 200 else else { // 503; // 500 alert( "A problem occurred with communicating between the " "XMLHttpRequest object and the server program. "+ "Please try again very soon"); 70
500Inter nal Server Error 404 URL Ajax request open URL request open try catch finally initreq function httprequest(reqtype,url,asynch){ // if(window.xmlhttprequest){ request = new XMLHttpRequest(); else if (window.activexobject){ request=new ActiveXObject("Msxml2.XMLHTTP"); if (! request){ request=new ActiveXObject("Microsoft.XMLHTTP"); //ActiveXObject request null // if(request){ initreq(reqtype,url,asynch); else { alert("your browser does not permit the use of all "+ alert("of this application's features!"); 71
/* */ function initreq(reqtype,url,bool){ try{ /*HTTP */ request.onreadystatechange=handleresponse; request.open(reqtype,url,bool); request.send(null); catch (err) { alert( "The application cannot contact the server at the moment. "+ "Please try again in a few seconds."); URL request open httpwww myorg com app open URL httpwww yourorg com try catch finally HACK #9 HTTP HTTP 1 1 descriptive 72
XMLHttpRequest request status HTTP HTTP Server Content Type HTTP URL HTTP Ajax HTML <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/tr/1999/rec-html401-19991224/strict.dtd"> <html> <head> <script type="text/javascript" src="js/hack7.js"></script> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>view response headers</title> <link rel="stylesheet" type="text/css" href="/parkerriver/css/ hacks. css"/> 73
</head> <body onload="document.forms[0].url.value=urlfragment"> <h3>find out the HTTP response headers when you "GET" a Web page</h3> <form action="javascript:void%200"> <p>enter a URL: <input type="text" name="url" size="20" onblur="getallheaders (this.value)"> <span class="message">::press tab when finished editing the field:: </span></p> <div id="msgdisplay"></div> </form> </body> </html> 1 13 URL text text onblur getallheaders URL URL hack7 js 74
var request; var urlfragment="http://localhost:8080/"; function getallheaders(url){ httprequest("get",url,true); //XMLHttpRequest onreadystatechange function handleresponse(){ try{ if(request.readystate == 4){ if(request.status == 200){ /* */ var headers = request.getallresponseheaders(); var div = document.getelementbyid("msgdisplay"); div.classname="header"; div.innerhtml="<pre>"+headers+"</pre>"; else { // 503 // 500 alert(request.status); alert("a problem occurred with communicating between "+ alert("the XMLHttpRequest object and the server program."); // if catch (err) { alert("it does not appear that the server is "+ alert("available for this application. Please "+ alert("try again very soon. \nerror: "+err.message); /* / function initreq(reqtype,url,bool){ try{ /* HTTP */ request.onreadystatechange=handleresponse; request.open(reqtype,url,bool); request.send(null); catch (errv) { alert( 75
"The application cannot contact the server at the moment."+ "Please try again in a few seconds." /* : reqtype:http. GET POST url: URL asynch: */ function httprequest(reqtype,url,asynch){ // if(window.xmlhttprequest){ request = new XMLHttpRequest(); else if (window.activexobject){ request=new ActiveXObject("Msxml2.XMLHTTP"); if (! request){ request=new ActiveXObject("Microsoft.XMLHTTP"); //ActiveXObject request null // if(request){ initreq(reqtype,url,asynch); else { alert("your browser does not permit the use of all "+ alert("of this application s features!"); handleresponse getallresponseheaders JSON 76
div if(request.status == 200){ /* */ var headers = request.getallresponseheaders(); var div = document.getelementbyid("msgdisplay"); div.classname="header"; div.innerhtml="<pre>"+headers+"</pre>";... header div classname CSS div.header{ border: thin solid black; padding: 10%; font-size: 0.9em; background-color: yellow span.message { font-size: 0.8em; CSS div div innerhtml pre 1 14 URL 77
HACK #10 HTML select URL URL text HTML <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/tr/1999/rec-html401-19991224/strict.dtd"> <html> <head> <script type="text/javascript" src="js/hack8.js"></script> <script type="text/javascript"> function setspan(){ document.getelementbyid("instr").onmouseover=function(){ this.style.backgroundcolor='yellow';; 78
document.getelementbyid("instr").onmouseout=function(){ this.style.backgroundcolor='white';; </script> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>view response headers</title> <link rel="stylesheet" type="text/css" href="/parkerriver/css/hacks. css"/> </head> <body onload="document.forms[0].url.value=urlfragment;setspan()"> <h3>find out the HTTP response headers when you "GET" a Web page</h3> <h4>choose the style for your message</h4> <form action="javascript:void%200"> <p> <select name="_style"> <option label="loud" value="loud" selected>loud</option> <option label="fancy" value="fancy">fancy</option> <option label="cosmopolitan" value="cosmo">cosmopolitan </option> <option label="plain" value="plain">plain</option> </select> </p> <p>enter a URL: <input type="text" name="url" size="20" onblur= "getallheaders(this.value,this.form._style.value)"> <span id="instr" class="message">«press tab or click outside the field when finished editing»</span></p> <div id="msgdisplay"></div> </form> </body> </html> 79
1 15 CSS hack css select text text id msgdisplay div hacks css div.header{ border: thin solid black; padding: 10%; font-size: 0.9em; background-color: yellow; max-width: 80% span.message { font-size: 0.8em; div { max-width: 80%.plain { border: thin solid black; padding: 10%; font: Arial, serif font-size: 0.9em; background-color: yellow;.fancy { border: thin solid black; padding: 5%; font-family: Herculanum, Verdana, serif; font-size: 1.2em; text-shadow: 0.2em 0.2em grey; font-style: oblique; color: rgb(21,49,110); background-color: rgb(234,197,49).loud { border: thin solid black; padding: 5%; font-family: Impact, serif; font-size: 1.4em; text-shadow: 0 0 2.0em black; color: black; background-color: rgb(181,77,79).cosmo { border: thin solid black; padding: 1%; font-family: Papyrus, serif; 80
font-size: 0.9em; text-shadow: 0 0 0.5em black; color: aqua; background-color: teal plainfancylouccosmo CSS fancy Ajax onblur getallheaders text select onblur="getallheaders(this.value,this.form._style.value)" this formstyle value select this value text hack8 js var request; var urlfragment="http://localhost:8080/"; var st; function getallheaders(url,styl){ if(url){ st=styl; httprequest("get",url,true); //XMLHttpRequest function handleresponse(){ 81
try{ if(request.readystate == 4){ if(request.status == 200){ /* */ var headers = request.getallresponseheaders(); var div = document.getelementbyid("msgdisplay"); div.classname= st == ""? "header" : st; div.innerhtml="<pre>"+headers+"</pre>"; else { // 503 // 500 alert(request.status); alert("a problem occurred with communicating between "+ alert("the XMLHttpRequest object and the server program."); // if catch (err) { alert("it does not appear that the server"+ "is available for this application. Please"+ " try again very soon. \nerror: "+err.message); /* httprequest() initreq() Hack #1, #2.. */ getallheaders st CSS plainfancyloudcosmo div classname st if(request.status == 200){ /* */ var headers = request.getallresponseheaders(); var div = document.getelementbyid("msgdisplay"); div.classname= st == ""? "header" : st; div.innerhtml="<pre>"+headers+"</pre>"; 82
CSS select header hacks css header 1 16 Cosmopolitan 1 17 83
HACK #11 DOM CSS iki HTML var request; 84
var urlfragment="http://localhost:8080/"; var st; function getallheaders(url,styl){ if(url){ st=styl; httprequest("get",url,true); /* DOM CSS2Properties : sttype ('plain', 'fancy', 'loud', 'cosmo') stylobj div.style HTML.stylObj div.style HTML.*/ function setstyle(sttype,stylobj){ switch(sttype){ case 'plain' : stylobj.maxwidth="80%"; stylobj.border="thin solid black"; stylobj.padding="5%"; stylobj.textshadow="none"; stylobj.fontfamily="arial, serif"; stylobj.fontsize="0.9em"; stylobj.backgroundcolor="yellow"; break; case 'loud' : stylobj.maxwidth="80%"; stylobj.border="thin solid black"; stylobj.padding="5%"; stylobj.fontfamily="impact, serif"; stylobj.fontsize="1.4em"; stylobj.textshadow="0 0 2.0em black"; stylobj.backgroundcolor="rgb(181,77,79)"; break; case 'fancy' : stylobj.maxwidth="80%"; stylobj.border="thin solid black"; stylobj.padding="5%"; stylobj.fontfamily="herculanum, Verdana, serif"; stylobj.fontsize="1.2em"; stylobj.fontstyle="oblique"; 85
stylobj.textshadow="0.2em 0.2em grey"; stylobj.color="rgb(21,49,110)"; stylobj.backgroundcolor="rgb(234,197,49)"; break; case 'cosmo' : stylobj.maxwidth="80%"; stylobj.border="thin solid black"; stylobj.padding="1%"; stylobj.fontfamily="papyrus, serif"; stylobj.fontsize="0.9em"; stylobj.textshadow="0 0 0.5em black"; stylobj.color="aqua"; stylobj.backgroundcolor="teal"; break; default : alert('default'); //XMLHttpRequest function handleresponse(){ try{ if(request.readystate == 4){ if(request.status == 200){ /* */ var headers = request.getallresponseheaders(); var div = document.getelementbyid("msgdisplay"); if(st){ setstyle(st,div.style); else { setstyle("plain",div.style); div.innerhtml="<pre>"+headers+"</pre>"; else { // 503 // 500 alert(request.status); alert("a problem occurred with communicating between "+ "the XMLHttpRequest object and the server program."); // if catch (err) { alert(alert("it does not appear that the server "+ 86
"is available for this application. Please "+ "try again very soon. \nerror: "+err.message); /* */ function initreq(reqtype,url,bool){ try{ /* HTTP */ request.onreadystatechange=handleresponse; request.open(reqtype,url,bool); request.send(null); catch (errv) { alert( "Your browser does not permit the use of all "+ "of this application s features!"); /* : reqtype: HTTP. GET POST url: URL asynch:, */ function httprequest(reqtype,url,asynch){ // if(window.xmlhttprequest){ request = new XMLHttpRequest(); else if (window.activexobject){ request=new ActiveXObject("Msxml2.XMLHTTP"); if (! request){ request=new ActiveXObject("Microsoft.XMLHTTP"); //ActiveXObject request null // if(request){ initreq(reqtype,url,asynch); else { alert("your browser does not permit the use of all "+ 87
"of this application's features!"); CSS HTML style div div style div div style fornfamilyarial setstyle Fancy div div URL text onblur CSS HTMLCSS hack10 js HTML <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/tr/1999/rec-html401-19991224/strict.dtd"> <html> <head> <script type="text/javascript" src="/parkerriver/js/hack10.js"> </script> <script type="text/javascript"> function setspan(){ document.getelementbyid("instr").onmouseover=function(){ this.style.backgroundcolor='yellow';; document.getelementbyid("instr").onmouseout=function(){ this.style.backgroundcolor='white';; </script> 88
<meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>view response headers</title> </head> <body onload="document.forms[0].url.value=urlfragment;setspan()"> <h3>find out the HTTP response headers when you "GET" a Web page</h3> <h4>choose the style for your message</h4> <form action="javascript:void%200"> <p> <select name="_style"> <option label="loud" value="loud" selected>loud</option> <option label="fancy" value="fancy">fancy</option> <option label="cosmopolitan" value="cosmo">cosmopolitan </option> <option label="plain" value="plain">plain</option> </select> </p> <p>enter a URL: <input type="text" name="url" size="20" onblur= "getallheaders(this.value,this.form._style.value)"> <span id="instr" class="message">«press tab or click outside the field when finished editing» </span></p> <div id="msgdisplay"></div> </form> </body> </html> onblur getallheader select cosmo URL Ajax 89
1 18 HTTP 1 19 URL Ajax 90