249 Head First Ajax ebook Free download

Gratis

0
0
478
3 months ago
Preview
Full text

ZHE DSS WR UHVSRQG

  Using Ajax, your pages and applications only ask the server for what they really need—just the parts of a page that need to change, and just the partsthat the server has to provide. „ Asynchronous requests allow more than one thing to happen at the same time.„ Only the part of a web page that needs to change gets updated.„ The page isn’t frozen while the server is returning data to the browser.

RI WKH EHQHILWV WKDW \RX FKHFNHG RII DERYH GR \RX

  We’ll need to make some changes to the existing XHTML page, code someJavaScript, and then reference the script in our XHTML. When we’re done, the page won’t need to reload at all, and only the things that need to change will getupdated when users click on the thumbnail images.

1 Modify the XHTML web page

  We need to include the JavaScript file we’re going to write and add some divs and ids, so our JavaScript can find and workwith different parts of the web page.thumbnails.js will contain function the JavaScript code we <html>getDetails { We’ll group thewrite for handling clicks on ... the thumbnail images and thumbnails into </html> } a <div>, so ourtalking to Rob’s server to JavaScript canget detailed information locate them on the oWe’ll use a <script> tag t page easily.reference thumbnails.js in our XHTML page.

2 Write a function to initialize the page

  window.onload occurs firstTo Do Modify the XHTMLStep 2: Initialize the JavaScript Initialize the page We need to create the thumbnails.js file, and add a JavaScript Create a request object function to set up the initial event handlers for each thumbnail image in Get the item’s details the inventory. 21you are here lots of ajax is just javascriptTo Do Modify the XHTMLStep 4: Get the item’s details Initialize the page Once a user clicks on an item in the inventory, we need to send a request to the server and ask for the description and details for that item.

1 The server usually returns data to Ajax requests

  Every time the server responds to a request, it sets the readyState property of the request object to a different value. To DoModify the XHTML Initialize the page Create a request object Get the item’s detailsDisplay the detailsthumbnails.jsfunction getDetails {...} displayDetails() Our callback function can use the response data...

A: You got it

  We’ll talk about that in the next chapter, but can you think of how arequest could be complete and still have a status code that indicates a problem? Q: Why would the server set theready state to 4 when the status code is something like 404?

Chapter 2. It’s okay if all of

  Get the server’s response from the request object’s responseText property } function displayDetails() { if (request.readyState == 4) {if (request.status == 200) { detailDiv = document.getElementById("description");detailDiv.innerHTML = request.responseText;}} } Since a server might set this value to 1 when it receives the request, and to 2 or 3 as it’sprocessing your request, you can’t be sure the server’s done unless readyStateis equal to 4. From page 31 We’ll send the server the name of the item, which is storedin the title attribute of that item’s image in the XHTML.

2 Thinking Ajaxian Welcome to Ajax apps—it’s a whole new web world

6R \RX¶YH EXLOW \RXU ILUVW $MD[ DSS DQG \RX¶UH DOUHDG\ WKLQNLQJ DERXW KRZ WR FKDQJH DOO \RXU ZHE DSSV WR PDNH UHTXHVWV DV\QFKURQRXVO\ %XW WKDW¶V QRW DOOWKHUH LV WR $MD[ SURJUDPPLQJ <RX¶YH JRW WR think about your applicationsdifferently mistakes DQG WKDW PHDQV rethinking \RXU HQWLUH DSSOLFDWLRQ¶V design. 'RLQJ WZR WKLQJV DW RQFH ZLWK $MD[ JRVK LW·VWKH EHVW %XW , PXVW DGPLW , KDYH WR WKLQN DERXW WKLQJV LQ D

ZKROH QHZ ZD\

  The problem is that if the username’s taken, the server responds with the initial page again, an error message... Users shouldn’t haveight fields to find out if the eld is valid.data in the first fi Right now the user fills out the form andclicks the “Register” button...

1 A new user fills out the registration form

  Technically you can write the code for these steps in any 2 2 Set up event handlers for the web form’s fields order, but this is the flowWe’ll need some initiational code to set up an onblur event for thethat the app will follow andusername field on the page. 3 3 Create and configure a new request object We can use the same createRequest() function from Chapter 1 to create the request, and then we’ll add the user’s requested username toWe skimmed this function the URL string to get that over to the server.in the last chapter, but 4 4 we’ll look at it in detailVerify the requested username in this chapter.

SUHVHQWDWLRQ DQG EHKDYLRU PDNHV

  iThis line tells the browser to call the ead byinitPage function as soon as the elements as soon as the script file is ron the page have been loaded.the web browser.window.onload = initPage; This tells the browserfunction initPage(){to call thedocument.getElementById("username").onblur =checkUsername()checkUsername;function when the user leaves We’ll look at getElementByID in} Here’s another case where the usernamedetail in Chapters 5 and 6. Let’s see how creating and using a and applications.request object looks in Mike’s movie review site: ary 1 Your page loads up and Most of these details vo application,handles application-specificfrom application t tionality,tasks and initialization.depending on func 2 Application-specific JavaScript layout, style, etc.gets called and needs to make a request to a server.

5 The server returns a response

  That’s a good thing,it parses any code that might call those utilities.but we’ve still got to figure out what all that codeinto a reusable Besides, it’s a nice way to keep things organized: is actually doing.utilities first, application-specific code second.set of functions.you are here good apps work on multiple browsersCreate a request object... This insulates the 2 2 calling code fromTry to create an XMLHttpRequest for non-Microsoft browsersall the messy Define a variable called request, and try to assign to it a new instance of thedetails of browser XMLHttpRequest object type.

4 If all else fails, return null

  So declare request asnull, and then let the calling code decide what to do about it. request = null; Returning null puts the burden on the calling code, which can This goes in the final catch block.

5 Put it together, and return request All that’s left is to return request. If things went okay, request points to a request object

  65you are here ajax is about interactionAjax app design involves both the web page AND the server-side program Even though there was already a web form for Mike’s registration page, we’ve got to interact with that form to get the user’s username, and later on,to update the page with an error message if the selected username’s taken. 6 6 Tell the browser what function to call when the server responds to the request This is the “callback.” We’ll 7 7 Tell the browser how to send the request to the server write it in a few pages.

VWDWXV7H[W

  status and statusText are used by the onreadystatechange is the property we use browser to tell your code the HTTPto tell the browser what function to call when the server responds to a request.status that was returned by the server, such as 200 for “OK,” when the serverthinks everything worked as it should, or 404 for “Not Found,” when the servercouldn’t find the requested URL. utils.jsrequestweb browserrequestcheckUsername() validation.js The browser web server communicates withThe checkUsername() function uses the server using thethe send() method of the request HTTP protocol.object to ask the browser to pass the request on to the server.

2 The server sends available along with a status code. readyState

  }} function showUsernameStatus() { if (request.readyState == 4) {if (request.status == 200) { if (request.responseText == "okay") {// if it's okay, no error message to show} else {// if there's a problem, we'll tell the user alert("Sorry, that username is taken.");}} the browser calls back your code you are here 77designing ajax applications Test Drive Add the showUsernameStatus() function to validation.js, and load the registration page in your browser. Suppose a user does just what you expect: they enter a username, and while an asynchronous request is going to the server andgetting handled by the browser, your callback is running, and the user’s filling out other information on the form.

2 The server returns a new page

expect the unexpected%XW ZH QHYHU WKRXJKW DERXW

XVHUV LJQRULQJ DOO RI WKH RWKHUILHOGV +RZ GR ZH NHHS XVHUV

  will do thingsFrank: ...and another when their username’s verified.exactly the way Jill: Hey, and if we used an image to show whether the username is okay or not, we could get rid of the alert when you do... if the server says the username is okay.if (request.responseText == "okay") { document.getElementById("status").src = "images/okay.png"; } else {alert("Sorry, that user name is taken."); We can ditch the document.getElementById("status").src = "images/inUse.png";alert popup ...in favor This graphic is shown if}of a nicer the username is taken.

LW IROORZ WKH SULQFLSOH RI VHSDUDWLQJ FRQWHQW IURP

  That involves just a few more changes to validation.js: By setting the disabled propertyDisable the Register buttonto true, the user can fill in the When a user first loads the page, the username hasn’t been checked. Sofields, but they can’t press the we can disable the Register button right away in our initialization code.submit button until we’re ready.function initPage(){ document.getElementById("username").onblur = checkUsername; document.getElementById("register").disabled = true;} Enable the Register button validation.js If the username is okay, the user’s ready to register, so we need to enable the Register button.

2 Word Search

designing ajax applicationsLabel MagnetsAll the labels describing what’s going on in the new-and- improved registration page fell to the ground. Can youplace the labels in the right place on the diagram?request = createRequest(); NotshowUsernameStatus()initialized

2 Response

  The status and At this stage, data isresponse headers are available.downloading into the By the time this statementrequest object, but it’s not is executed, the requestquite ready to be used yet.object knows how to connect and what to connect to. When the user leaves a field, an event functioncreates a request object.request = createRequest(); The server responds with a readyState of 2 while it’s workingNotshowUsernameStatus()on the problem.

2 By the time this statement

  Also, see if you can design the site so when acustomer clicks on a class level, the description and a picture of just the selected class is displayed. Also, you should have designed the site so that when a customer clickson a class level, the schedule, description, and a picture of just the selected class is displayed.

A: JavaScript, and a request object to fetch the schedule from the server

  100Chapter 3 javascript eventsAjax apps are more than the sum of their parts Ajax apps are really just a combination of lots of pretty simple technologies: XHTML, CSS, JavaScript, and things like the DOM, which you’ll get to in a few chapters. Mon Tue Wed Thu Fri Intermediate 5pm-6pm X X X 6pm-7pmX 8pm-9pm X Advanced EnrollWeb server Web page Sending the request to the server involves a JavaScript event handler,Most of the event handling on the as well as a request object.aScript, buttons and tabs will be Jav The main content pane for each t object.and it won’t need a reques class is XHTML.

3 Events are the key to interactivity

  106Chapter 3 javascript eventsConnect events on your web page to event handlers in your JavaScript You’ve already used the window.onload event to trigger lots of setup workAll of these on web pages, and the onclick event to handle users clicking on an image.functions will go We can use these events, as well as the onmouseover event, to connectin our schedule.js different parts of Marcy’s yoga page to JavaScript functions we’ll write.script... Just be sure you leave any parentheses off the name of the function: The best way to assign event handlers is by using properties of the elements in your XHTML page, anddoing that assignment in a function that runs before the user gets control of a page.

3 Use your XHTML’s content and structure showHint() is called when a user rolls their mouse over a tab or image

  Our default can just be a generic instruction message.var = "Click a tab to display the course schedule for the class"; hintText }o getvar contentPane = ("content");getElementById All that’s left is t the <div> where the.innerHTML = "<h3>" + + "</h3>";contentPane hintTextcontent is shown, and t. To make a tab active, we need to change the tab’s background to the “active” color All we need to do to make a different tab active is change it to the active color.

KDSSHQHG WR DOO WKDW EXVLQHVV DERXW

  } function showHint() {// showHint() stays the same }function hideHint() { // hideHint() stays the same} 122Chapter 3 javascript eventsfunction showTab() { This is the same loop as in ll the initPage(). Assume the schedule is an HTML description and a table that shows the days of the week that the selected class isavailable.

VFKHGXOH DQG GHVFULSWLRQ LV +70/ ZHVKRXOG VWRUH WKDW DV DQ +70/ SDJH

  126Chapter 3 javascript eventsUse a request object to fetch the class details from the server The server doesn’t need to do any processing for Marcy’s page, but we can still use a request object to grab the XHTML fragments for each class. // set each tab's CSS classvar request = createRequest(); This is the same request creation if (request==null) { code we’ve been using for talking to server-side programs alert("Unable to create request"); return; } request.onreadystatechange = showSchedule; request.open("GET", selectedTab + ".html", true); request.send(null); equest object } This time we’re sending the r o name the to a page URL.

3 Be careful when you have two functions

  "<h3>Click a tab to display the course schedule for the class</h3>";This reallyelse } { ...otherwise, the welcome pane is a hack...will have a class schedule, and we’re puttingwelcomePaneShowing = false;it won’t even be clear which presentationte If any other tab is selected, upda class is showing! We just need to change back to the default state, whichis no CSS class: function buttonOut() { this.className = "";} When you initialize the page, you need to assign the new event handlers Now we need to assign the new functions to the right events.

Chapter 4 showHint() is not getting run

  We need a way to assign more than one handler to an event, which means we can’t just assigna handler to an event property. This should be a method on any element “on” in front.function in your script, or you you have an objectcan declare the function inline.representation for.

ZKLFK WKH KDQGOHUV DUH UXQ ZLOO DIIHFW KRZ \RX

  ZULWH \RXU FRGH" 142Chapter 4 multiple event handlersDOM? What’s that?

Q: Q: Q:

  Ideally, DOM navigation quite a bit in Chapter 6.specifications standardize a process and Right now, though, you don’t really needremove any possible guesswork.works in any webto worry too much about what level of the DOM you’re using, except to make sure Why are the event property namesQ:browser thatyour browser supports that level. 143you are here firefox and safari are dom level 2 browsersYour objects can have multiple event handlers assigned to a single event in DOM Level 2 The most important thing that DOM Level 2 added to events is the ability for an event to have more than one handler registered.

Dokumen baru