Xem mẫu

Showing Processing Status error,Could not verify your login information. Our client-side code parses this result and either redirects to the main application page, or displays the error message for the user. Also note that we set Content-Type to text/plain, so XMLHttpRequest won’t expect the response to contain valid XML. Of course, this is a really basic example. You could certainly expand it to return different error messages or codes, or to direct different classes of users to different parts of the application (for example, logging administrative users into an admin console). You could also choose a different separator character. Sometimes, your data will contain commas, so using a comma as a separator may not be a good idea. The pipe character (|) is another popular choice. The CSV format is simple, yet flexible enough to deal with a wide range of uses—any case in which you have a limited number of data fields and you control the code on both the back end and the front. XML is better suited to more complicated types of data, and situations in which your application has to com-municate with other applications. Showing Processing Status While our fake processing page is pretending to authenticate the submitted data, users will be staring at the login screen, wondering what the heck is going on. This is where status notification again comes to the fore. It’s vital to let users know what’s going on with an application, but it’s particularly important in the case of an AJAX app, as users have to sit and wait for processes on the server to finish. If the application is busy performing some task, it should look busy to the user. On this login page, we’ll use an animation effect to indicate that the application is processing the user’s request, but we’ll take a slightly different approach to the one we used last time. Rather than creating a sense of movement by changing the animation’s opacity, we’ll use a line of dots similar to an ellipsis (…), animat-ing them a bit like a line of Christmas lights, as shown in Figure 4.3. This is a pretty common look for a processing animation, and it has the advantage of being very lightweight, since it’s all text. 107 Licensed to siowchen@darke.biz Chapter 4: AJAX and POST Requests Figure 4.3. Creating animation by appending a string of dots The showStatusPrompt method starts off the status animation. This code sets the prompt message to “Processing,” then starts up the setInterval process that animates the dots. Here’s the code: File: applogin.js (excerpt) this.showStatusPrompt = function() { var self = Login; self.dots = ``; self.setPrompt(`proc`, `Processing`); self.promptInterval = setInterval(self.showStatusDots, 200); }; Again, the return value of the setInterval call is the interval ID we’ll need to turn off the animation, so we save it for future use in the promptInterval property. The setInterval process is set to call showStatusDots every 200 milliseconds. Here’s the showStatusDots code: File: applogin.js (excerpt) this.showStatusDots = function() { var self = Login; var dotSpan = self.dotSpan; self.dots += `.`; if (self.dots.length > 4) { self.dots = ``; } if (dotSpan.firstChild) { dotSpan.removeChild(dotSpan.firstChild); } dotSpan.appendChild(document.createTextNode(` ` + self.dots)); }; 108 Licensed to siowchen@darke.biz Handling the Server Response The action in this code occurs in two parts. The first part sets up the dot string for display; the second part displays the string after the word “Processing” in the prompt box. The process of animating the dots starts with an empty string; a dot is appended to this string over and over, so that the line of dots grows. When the number of dots exceeds four, the code resets the string to be empty, and starts the process over. These dots appear in a span element that appears immediately to the right of the word “Processing” in the prompt, so it looks like the entire string of text is animated. The movement of the dots draws the user’s eye to the word “Pro-cessing,” which makes it more likely that the user will read and understand the prompt. The constantly changing row of dots provides another hint to the user that the application is busy doing something. Handling the Server Response When the response arrives back from the server, the result is passed to the handleLoginResp method as a string. This method parses the CSV-formatted result string by splitting it at the comma and restoring the respType and respMsg values we had on the server side in applogin.php: File: applogin.js (excerpt) this.handleLoginResp = function(str) { var self = Login; var respArr = str.split(`,`); var respType = respArr[0].toLowerCase(); var respMsg = respArr[1]; if (respType == `success`) { location = respMsg; } else { self.showErrorPrompt(respMsg); } }; This provides the status of the response in respType, and the meat of the re-sponse—either an error message or redirect path—in respMsg. Once we know whether this response indicates success or an error, we know what to do with the response content in respMsg. If the login was successful, the code will redirect the browser to whatever path the server returned in respMsg. If the response indicates an error, respMsg will 109 Licensed to siowchen@darke.biz Chapter 4: AJAX and POST Requests instead contain an error message, and handleLoginResp will hand it off to the showErrorPrompt method for display. Taking Care of Case-sensitivity With a string variable like respType that contains some sort of named status (e.g., success or error), it’s usually a good idea to get into the habit of converting the string to upper- or lowercase before checking the value. This takes care of any case-sensitivity issues that might occur if either you, or someone you work with, use the wrong case or mixed case somewhere else in the code. Dealing with Login Failures The showErrorPrompt method displays an error to users when their logins fail, and resets the login interface to make it easy for them to try logging in again: File: applogin.js (excerpt) this.showErrorPrompt = function(str) { var self = Login; var dotSpan = self.dotSpan; clearInterval(self.promptInterval); if (dotSpan.firstChild) { dotSpan.removeChild(dotSpan.firstChild); } self.setPrompt(`err`, str); self.form.Pass.value = ``; }; After declaring and initializing a couple of variables, showErrorPrompt stops the moving dots animation by calling clearInterval with the animation process’s interval ID. Then, as the animation may have been stopped while displaying dots, showErrorPrompt uses removeChild to clear any dots that may be left in the animation’s span. The next thing we need to do is to set the prompt to the error text that’s come back from the server, and to set the prompt type to err so it will display in the proper style. We achieve this with a call to setPrompt. Last of all, the code resets the user interface by clearing out the Password field so that users can quickly and easily re-enter their passwords and attempt another login. This is another addition that’s important to the usability of the app, as it saves your users time and irritation. Most often, login errors (for valid users) arise 110 Licensed to siowchen@darke.biz Dealing with Login Failures from the mistyping of passwords, so when a login attempt fails, the code empties the text in the password field, to save the user from having to delete it manually. Now that we’ve sent the request, set up an animation to indicate that the server is busy, and handled both successful and unsuccessful login attempts, our basic login application is ready to go! Open applogin.html in your web browser and try to log in with bogus details. You should see the animated dots, followed by the “Could not verify your login information” message shown in Figure 4.4. Figure 4.4. A failed login attempt If you log in using the login ID user and the password password, you’ll be redir-ected away from applogin.html to a page named appmainpage.php—the main page of your application. Great! You now have a fully functional application login form. There’s no chance that users can submit details without filling in both the Login ID and Password fields, and the app keeps users informed about what’s going on behind the scenes. It also works in modern versions of Internet Explorer, Firefox, Safari, and Opera. In fact, the only browsers on which it doesn’t work are screen readers used by the vision-impaired. However, contrary to popular belief, there’s no reason why our AJAX can’t work in those browsers, too. 111 Licensed to siowchen@darke.biz ... - tailieumienphi.vn
nguon tai.lieu . vn