1. Trang chủ
  2. » Công Nghệ Thông Tin

THE BOOK OF JAVASCRIPT, 2ND EDITION phần 7 pps

44 296 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 44
Dung lượng 552,33 KB

Nội dung

extra text nodes in place but just skip nodes that it doesn’t care about For example, when looking for the translation of an English word, the code in Figure 15-6 could loop through the children of the parent of the english element, checking the nodeName of each child and stopping when it finds an element named translation As it is now, the code in Figure 15-6 works fine because the XML files I created not have a space between the english and translation elements For our purposes, this works In the real world, however, you would want to write code that would deal with the possibility that somebody writing an XML dictionary for your application would accidentally put a space between the english and translation elements Creating a Suggest Application for Translation Let’s apply what we’ve learned so far to another example of using XML with Ajax Google Suggest is a very fancy web application, with many interesting features that help it react quickly to user queries As shown in Figure 15-4, Google Suggest provides suggested searches as you type letters into the search box Although the JavaScript I’ll describe in this section is not nearly as advanced as what you see in Google Suggest, it should help to demonstrate how Google Suggest works Figure 15-10 shows a simplified suggest application that translates English words into Italian The figure shows how things look in Internet Explorer after I type bo On the left side you see a list of the first ten English words in the dictionary that start with the letters bo, and on the right side are their translations After each keypress, the script reloads the italian.xml file and looks for words that begin with whatever letters are in the text box As is typical with Ajax, there is no submit button to push; the JavaScript accesses the information it needs and updates the page as I type Figure 15-10: The translation script with suggestions 292 Chapter 15 NOTE For a full description of how Google Suggest works, see Chris Justice’s excellent analysis at http://serversideguy.blogspot.com/2004/12/google-suggest-dissected.html The code for this neat little application can be found in Appendix D and is available at http://www.bookofjavascript.com/Chapter15/translator.html It is a bit long, so I will break it up a bit as I describe it here NOTE Remember, this code will not work if you are testing it in Internet Explorer unless you serve up the italian.xml file using a webserver If you don’t have access to a webserver and you want to test the script out, make sure to make the change described in the section “Internet Explorer, responseXML, and Client-Side Ajax” on page 291 Let’s begin with the text entry form: This form has one text input element and a div into which the results of the script will be placed The ems you see in the style of the div set the width of the div equal to some multiple of the width of the letter m (em) in the font being used The size of the em unit will vary with the font being used, in direct proportion to the width of the letter m in that font As a result, if a user changes the font size on his or her browser, the script will automatically adjust the width of the div The JavaScript code will automatically change the height of the div as the number of results to be shown changes Notice that the text input element has an onKeyUp event handler When a letter is typed (that is, a key is pressed), and then released, the getTranslations() function is called upon the release of the key This function is almost exactly like the getTranslationFromFile() function shown in Figure 15-6 except for the anonymous function defined after , which has been changed to: request.onreadystatechange = function() { if (request.readyState == 4) { xml_response = request.responseXML; displayResults(findTranslations(xml_response, the_word)); } } When the state of the request object changes to 4, it has completely downloaded the requested document At this point it calls findTranslations() to get the relevant words and translations, and then it sends those results to the displayResults() function X M L i n J a v aS c ri p t a n d A j a x 293 Finding the Translations The findTranslations() function searches through the XML file for the correct words to display Figure 15-11 is a slightly abridged version: function findTranslations(xml_doc, the_word) { // obvious variable declarations and initializations (omitted) var these_translations = new Array(); var english_word_elements = xml_doc.getElementsByTagName("english"); var reg_exp = new RegExp("^" + the_word); while ((loop < english_word_elements.length) && (found == false)) { this_word = english_word_elements[loop].firstChild.nodeValue; if (reg_exp.test(this_word)) { the_translation = english_word_elements[loop].nextSibling.firstChild.nodeValue; found = true; } loop++; } if (found == true) { these_translations.push(this_word + "\t" + the_translation); for (var count = loop; count < (loop + 10); count++) { if (count < english_word_elements.length) { this_word = english_word_elements[count].firstChild.nodeValue; if (reg_exp.test(this_word)) { the_translation = english_word_elements[count].nextSibling.firstChild.nodeValue; these_translations.push(this_word + "\t" + the_translation); } } } } return these_translations; } Figure 15-11: Finding the translations The findTranslations() function shown in Figure 15-11 is similar to the findTranslations() function shown in Figure 15-6, except that instead of getting just one translation for a word, it looks for up to ten words that begin with the letters in the text box, with their translations If only seven words begin with the letters in the text box, only those seven words will be displayed The function uses regular expressions (discussed in Chapter 11) to determine whether a word starts with the letters in the box ( ) Next, it gets a list of all the XML elements named english and loops through that list until either it runs out of elements or it finds a word that matches the regular expression ( ) Each time through the loop, this_word is set to the English word ( ), and then checks to see whether this_word matches the regular expression If it does, the translation of the word is retrieved from the english element’s sibling, the found variable is set to true, and the loop ends 294 Chapter 15 At the end of the loop, checks to see whether a word has been found that matches the regular expression If so, sticks the word, followed by a tab (\t) and the word’s translation at the end of an array called these_translations The these_translations array now has one word and its translation, and it will eventually contain all the words and translations to be displayed NOTE The push() method ( ) is a handy way to add something to the end of an array; it pushes an element to the end Once the retrieved word and translation have been added to the array, it’s time to find other words that begin with the letters in the text field The loop in begins by examining the items in the array of english elements, starting where the previous loop left off It then looks at the next nine items Each time through the loop, the code gets the next english element, checks to see whether it matches the regular expression, and if so, adds it and its translation to the these_translations array The code in makes sure the loop ends if there are no more elements in the array of english elements to consider, which may happen, for example, if we are looking at words that begin with the letter z When the loop in ends, the function exits and returns the these_ translations array, which is then fed into the displayResults() function Displaying the Results The function displayResults(), which displays the results, is pretty straightforward (as shown in Figure 15-12) The function first creates an HTML table and then inserts that table into the innerHTML of theResultsDiv The only tricky thing about this script involves changing the size of the div so that its border expands and contracts as the table changes size function displayResults(the_results) { var display_me = ""; var splitter; var this_result = null; for (var loop = 0; loop < the_results.length; loop++) { this_result = the_results[loop]; if (this_result != null) { splitter = this_result.split("\t"); display_me += "" + splitter[0] + "" + splitter[1] + ""; } } document.getElementById("theResults").style.height = (the_results.length + parseInt(the_results.length / 5) + 1) + "em"; document.getElementById("theResults").innerHTML = "" + display_me + ""; } Figure 15-12: Displaying the results X M L i n J a v aS c ri p t a n d A j a x 295 The displayResults() function is passed an array of results to display The code in loops through this array, setting this_result to the next result each time it goes through the loop NOTE Remember that each result is an English word, followed by a tab and the word’s translation in Italian (see in Figure 15-11) The split() method in is a built-in method of String objects Given a character, or a set of characters, the split() method divides a string into parts and stores those parts in an array For example, the instance of split() in takes the string in the_result and divides it into two parts: the part before the tab (\t) and the part after the tab These pieces are stored in an array called splitter; splitter[0] contains the part before the tab, and splitter[1] contains the part after the tab The code in then takes these parts, creates a string representing a row in an HTML table, and adds this string to the display_me variable, which will contain all the rows of the table Once the loop completes, changes the height property of the div’s style property, making it roughly as tall as the table that it will contain The formula in gives an approximation of the div’s height; it says that the div’s height should equal the number of rows in the table plus a little bit for the space between the rows The number of rows in the table, in turn, equals the number of items in the the_results array Finally, puts the beginning and ending table tags on the table and puts the table into the innerHTML of the div There’s a great deal more to Google Suggest, including choosing an element from the suggestion box, caching results to make the page react more quickly, and filling in a few letters in the text box With the JavaScript you know now, and a little expertise with cascading style sheets, you should be able to add those features to your own applications Summary This chapter has covered the basics of using XML with JavaScript and Ajax: What XML is used for How to format XML documents How Ajax applications use XML to share data How to process XML with JavaScript How to deal with cross-browser XML issues The chapter has also given you more details about some objects you’ve already encountered: How to use the split() method to divide a string into parts How to use the push() method to add an element to the end of an array How to use em in a cascading style sheet to make the size of something proportional to the font being used 296 Chapter 15 Now that you know how to perform Ajax calls from the browser, and how to format XML documents and process them with JavaScript, it’s time to complete the Ajax cycle and learn about server-side programs First, however, you should practice your Ajax skills with the following assignment Assignment Write an Ajax address book like the one shown in Figure 15-13 First, create an XML file that is to be your address book Each person should have a name, a home address, a phone number, and an email address When the web page opens, it should get the names of the people in the XML file and then put them into the select field When a user clicks a name in the select field, Ajax should look up that person in the phone book and display the results in the spans below the select box Figure 15-13: An Ajax-enabled address book X M L i n J a v aS c ri p t a n d A j a x 297 SERVER-SIDE AJAX In Chapter 15 we saw how Ajax can enhance your user’s experience by making asynchronous requests for information In that chapter we focused entirely on client-side Ajax In this chapter we’ll focus on using Ajax to communicate with programs on webservers, which I will also call server-side programs This chapter explains: What server-side programs can for you Different types of requests The basics of PHP, a server-side programming language How to use PHP to read and save files on webservers What to if the webserver you are contacting doesn’t respond How to update the contents of a web browser automatically when a server-side file changes Real-World Examples of Server-Side Ajax Almost all examples of Ajax on the Web involve communications between a web browser and a program running on a webserver For example, when you search for a restaurant using Google Maps, Google’s webservers provide the maps and determine where the icon showing the restaurant’s location should go The Ajax-driven To Do list site, http://www.tadalist.com, lets you create To Do lists and then share them so that others (whether in your household or organization) can add tasks, mark completed tasks, and so on Figure 16-1 shows my Book of JavaScript To Do list At the top are uncompleted items (don’t tell my publisher!), and below those are finished items (I’m still waiting to celebrate; any day now, for sure.) Figure 16-1: A Ta-da List To Do list Figure 16-2 shows the screen after I click the Add Another Item link As you can see, a text field and an Add This Item button appear When I click the button, the new item appears on the bottom of the To Do list and is saved on the Ta-da List webserver When I exit the browser and then return to the site, the saved To Do list is read from the Ta-da List webserver and displayed in my browser When we covered cookies in Chapter 12, we saw examples of how to store a user’s information For example, when a visitor bought clothing using the shopping cart, the items the visitor bought were stored on the visitor’s hard drive Then, when it was time to purchase the selected items, the checkout page retrieved this stored information and told the visitor how much was owed The difference in the To Do list example is that rather than saving the information on the computer of the person using the web page, the application saves the information on the Ta-da List webserver As you may recall, browsers limit the amount of information you can save in a cookie on a visitor’s 300 Chapter 16 hard drive to about 80 kilobytes In contrast, the amount of information stored on a webserver’s hard drive is limited only by the amount of space on the hard drive Another difference between saving information in a cookie on a user’s hard drive and saving it on a webserver’s hard drive is that information on a webserver can be shared by anybody who accesses that server with his or her web browser Figure 16-2: Adding a new item to the To Do list Notice the Sharing link at the right end of the navigation bar at the top of the list in Figures 16-1 and 16-2 When the link is clicked, it brings up a page that allows you to input an email address for the person you want to set up as a sharer Ta-da List then emails a code to that address that lets the recipient modify the list you’ve shared Sharing is made possible because both you (the list owner) and the list sharer are using web browsers to alter information that is shared on a single, remote webserver that anyone with the correct code can access In this chapter I’ll teach you what you need to know to build your own collaborative To Do list Ajax application However, since such an application is complex and involves a fair amount of code (which pulls together elements from every chapter of this book), I will cover the application in depth only in Chapter 17 The Power of Webservers Until now, we have focused on JavaScript programs, which run in a web browser These programs can save information on the local computer and rely on the local computer for their system resources This chapter will focus on programs that run on webservers—programs that save information to a remote server and rely on that webserver for much of the heavy lifting Server-Side Aj ax 301 Recall from Chapter that the getTime() method of a Date object returns the number of seconds between the time the method is called and January 1, 1970; a number that will differ every second Setting a parameter such as ignoreMe equal to the results of getTime() makes the URL different every time the URL is used This will trick Internet Explorer into thinking it’s a new URL, inducing IE to update the page We’ll see an example of this trick in Figure 16-15 File Handling in PHP PHP programs can read and manipulate files that reside on webservers With PHP, you can read a text file, create a new text file, and edit the text in a file on the server Once a file is created on a webserver, it can be accessed by any web browser When a webserver file is edited, those edits will be seen by anyone looking at the file Creating and Adding Contents to a Text File with PHP To use PHP to create a new text file, or to change the contents of an existing text file, you must: Open the file and signify that you want to write contents to the file Write text to the file Close the file To open a file for writing, use PHP’s fopen() function This function takes two parameters: the name of the file you want to open and either a "w" if you want to replace the existing contents of that file with new text, or an "a" if you want to add text to the end of the file The fopen() function returns a value, which you can use in your PHP program to refer to the file you’ve just opened For example, to open myFile.txt for writing, use this line: $myFile = fopen("myFile.txt", "w"); NOTE When you open a file with "w" as the second parameter, the old contents of the file are deleted Therefore, if you want to edit the contents of a file, you should first read the contents of the file into a variable, then edit the contents of the variable, and then write the contents back to the file We’ll be doing this in Chapter 17 Once a file has been opened, use the PHP function fwrite() to write to it This function takes the value returned by the fopen() function and the string you want to write to the file The function returns either TRUE or FALSE, depending on whether or not it succeeded in writing to the file (Writing may fail for several reasons: the hard drive might be full, or the webserver might not have permissions to write to the file.) For example, to write two lines to the file you opened above, use this line: $success = fwrite($myFile, "line one\nline two"); Server-Side Aj ax 321 The \n puts a line break into the file, which creates a two-line file in this case If the write is successful, $success will contain the value TRUE; if not, it will contain the value FALSE Once you’ve written to a file, close it with fclose(): fclose($myFile); Combining these lines gives you the PHP script below: One of the more pernicious problems you’ll encounter when dealing with server-side programming is that of ensuring that your webserver has permission to alter the files you want to alter Sometimes a PHP program can fail to write to a file because the webserver running it does not have access to that particular file If this happens, PHP will give an error like this: Warning: fopen(yourFile.txt) [function fopen]: failed to open stream: Permission denied File permissions work differently on different operating systems If you get this kind of error, refer to your operating system’s manuals to determine how to inspect and modify file permissions Reading Files in PHP It’s a bit trickier to read a file using PHP than it is to write to a file The complication arises because the contents of a file are read line by line, and PHP needs to know when it has reached the end of a file so that it can stop reading Luckily, the PHP function feof() will tell PHP when it has reached the end of a file This function takes a variable that points to an open file (such as $myFile) and returns TRUE when the end of the file has been reached Figure 16-13 shows an example of PHP reading a file nestor cup King of Pylos, fought the centaurs nestor odysseus horsie Hero of the Iliad and Odyssey odysseus nestor Figure 17-7: XML representing information about users Let’s walk through this file As with all valid XML files, the first line ( ) declares that this is an XML file Line declares the one root element in the file, users The usernames odysseus and nestor follow in , inside the beginning and ending tags; these are the two users who have signed up for our application so far Each username is followed with some specific information about that user including (but not limited to) a name, a password, a profile, and the lists to which that user has access This XML file is updated whenever the user information changes; for example, if a new user joins, or if one user permits another to see his or her list NOTE This partial version of the application does not have a “join” feature; adding one will be part of your homework If it had such a feature, the file would update with information related to new users when they create an account in our application To Do List File The second type of XML file contains information about a user’s To Do list Each user owns one file, the name of which is based on the username For example, Figure 17-8 shows the contents of odysseus.xml, which contains all the To Do list information shown in Figure 17-4 odysseus Putting It A ll Together in a S hared To Do Li st 335 ... which the results of the script will be placed The ems you see in the style of the div set the width of the div equal to some multiple of the width of the letter m (em) in the font being used The. .. that the div’s height should equal the number of rows in the table plus a little bit for the space between the rows The number of rows in the table, in turn, equals the number of items in the the_results... contents of the file are deleted Therefore, if you want to edit the contents of a file, you should first read the contents of the file into a variable, then edit the contents of the variable, and then

Ngày đăng: 06/08/2014, 16:23

TỪ KHÓA LIÊN QUAN