In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "what is the method of JavaScript specifying callback". In daily operation, I believe many people have doubts about what the method of JavaScript designated callback is. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "what is the method of JavaScript specified callback?" Next, please follow the editor to study!
A glimpse of Web 2.0
We need a way to send requests and receive responses that contain only the data we need instead of the entire HTML page.
Most interactions include adding details to an existing page, modifying the body text, or overwriting the original data. In these cases, the Ajax and Web 2.0 methods allow data to be sent and received without updating the entire HTML page.
Introduction to XMLHttpRequest
XMLHttpRequest: a JavaScript object that is at the heart of Web 2.0, Ajax, and most other content. Here are a few methods and properties that will be used for this object:
Open (): creates a new request to the server. Send (): sends a request to the server. Abort (): exit the current request. ReadyState: provides the current HTML ready state. ResponseText: the request response text returned by the server.
What do you do with XMLHttpRequest? These methods and properties are related to sending requests and processing responses. In fact, if you look at all the methods and properties of XMLHttpRequest, you will find that they are related to a very simple request / response model.
First you need to create a new variable and assign it an instance of the XMLHttpRequest object.
Listing 1. Create a new XMLHttpRequest object
Var request = new XMLHttpRequest ()
JavaScript doesn't require you to specify a variable type, so you don't need to do it like listing 2 (which you might need in the Java language).
Listing 2. Create Java pseudo code for XMLHttpRequest
XMLHttpRequest request = new XMLHttpRequest ()
So create a variable in JavaScript with var, give it a name (such as "request"), and then assign it a new XMLHttpRequest instance. You can then use the object in the function.
Error handling
In fact, all kinds of things can go wrong, and the above code does not provide any error handling. A better approach is to create the object and exit gracefully if something goes wrong. For example, any older browsers (believe it or not, there are still people using older versions of Netscape Navigator) do not support XMLHttpRequest, and you need to let these users know that something is wrong. Listing 3 shows how to create this object to issue a JavaScript warning if something goes wrong.
Listing 3. Create XMLHttpRequest with error handling capability
Var request = false; try {request = new XMLHttpRequest ();} catch (failed) {request = false;} if (! request) alert ("Error initializing XMLHttpRequest!")
Be sure to understand these steps:
1. Create a new variable request and assign the value false. False will be used later as a decision condition, which indicates that the XMLHttpRequest object has not been created yet. 2. Add try/catch block: 1) try to create a XMLHttpRequest object. 2) if it fails (catch (failed)), make sure that the value of request is still false. 3. Check whether request is still false (if everything is normal, it won't be false). 4. If there is a problem (request is false), use the JavaScript warning to notify the user that there is a problem.
Now that you have a piece of XMLHttpRequest object creation code with error checking, you can tell you what went wrong.
With Microsoft, we need to deal with Microsoft browsers in a different way. Listing 4. Add support for Microsoft browsers
Var request = false; try {request = new XMLHttpRequest ();} catch (trymicrosoft) {try {request = new ActiveXObject ("Msxml2.XMLHTTP");} catch (othermicrosoft) {try {request = new ActiveXObject ("Microsoft.XMLHTTP");} catch (failed) {request = false } if (! request) alert ("Error initializing XMLHttpRequest!")
It's easy to be fascinated by these curly braces, so here's each step:
1. Create a new variable request and assign the value false. Using false as a judgment condition, it indicates that the XMLHttpRequest object has not been created yet. 2. Add try/catch block: 1) try to create a XMLHttpRequest object. 2) if it fails (catch (trymicrosoft)): 1 > try to create an Microsoft compatible object (Msxml2.XMLHTTP) using a newer version of the Microsoft browser. 2 > if it fails (catch (othermicrosoft)), try to create an Microsoft compatible object (Microsoft.XMLHTTP) using an older version of the Microsoft browser. 2) if it fails (catch (failed)), make sure that the value of request is still false. 3. Check that request is still false (if all goes well, it won't be false). 4. If there is a problem (request is false), use the JavaScript warning to notify the user that there is a problem.
After modifying the code in this way, before experimenting with Internet Explorer, you should see the form that has been created (without error messages).
Static and dynamic
Take a look at listings 1, 3, and 4 again, and notice that all of this code is nested directly within the script tag. JavaScript code like this that is not placed in the body of a method or function is called static JavaScript. This means that the code runs at some point before the page is displayed to the user. Although it is not possible to know exactly when the code runs and how it affects the browser according to the specification, it is guaranteed that the code will run before the user can interact with the page. This is also the general way most Ajax programmers create XMLHttpRequest objects
That is, you can also put this code in a method as shown in listing 5.
Listing 5. Move the XMLHttpRequest creation code to the method
Var request; function createRequest () {try {request = new XMLHttpRequest ();} catch (trymicrosoft) {try {request = new ActiveXObject ("Msxml2.XMLHTTP");} catch (othermicrosoft) {try {request = new ActiveXObject ("Microsoft.XMLHTTP");} catch (failed) {request = false } if (! request) alert ("Error initializing XMLHttpRequest!");}
If you code in this way, you need to call this method before dealing with Ajax. So you also need code like listing 6.
Listing 6. Using the creation method of XMLHttpRequest
Var request; function createRequest () {try {request = new XMLHttpRequest ();} catch (trymicrosoft) {try {request = new ActiveXObject ("Msxml2.XMLHTTP");} catch (othermicrosoft) {try {request = new ActiveXObject ("Microsoft.XMLHTTP");} catch (failed) {request = false } if (! request) alert ("Error initializing XMLHttpRequest!");} function getCustomerInfo () {createRequest (); / / perform a series of operations using the request variable}
The only problem with this code is that error notification is delayed, which is why most Ajax programmers do not adopt this approach. Suppose a complex form has 10 or 15 fields, selection boxes, and so on, and some Ajax code is activated when the user enters text in the 14th field (from top to bottom in the order of the form). Running getCustomerInfo () at this point attempts to create a XMLHttpRequest object, but (in this case) fails. Then a warning is displayed to the user, explicitly telling them that they cannot use the application. But users have spent a lot of time entering data in the form! This is very annoying, and annoying obviously won't attract users to visit your site again.
If you use static JavaScript, users will quickly see an error message when they click on the page. It's annoying, too, isn't it? It may make the user mistakenly think that your Web application cannot run on his browser. However, it is certainly better than spending 10 minutes typing information and then displaying the same error. Therefore, I recommend writing static code so that users can find the problem as early as possible.
Send a request with XMLHttpRequest
Once you have the request object, you can enter the request / response loop. Remember, the only purpose of XMLHttpRequest is to let you send requests and receive responses. Everything else is the job of JavaScript, CSS, or other code on the page: changing the user interface, switching images, and interpreting the data returned by the server. Once the XMLHttpRequest is ready, you can send the request to the server.
Welcome to the sandbox.
Ajax adopts a sandbox security model. Therefore, the Ajax code (specifically the XMLHttpRequest object) can only send requests to the same domain. Security and Ajax will be covered further in future articles, and now you just need to know that code running on the local machine can only send requests to server-side scripts on the local machine. If you want your Ajax code to run on http://www.breakneckpizza.com/, you must send a request from a script running in http://www.breakneck.com/.
Set up server URL
The first step is to determine the URL of the connected server. This is not a special requirement of Ajax, but it is still necessary to establish a connection, and obviously you should know how to construct URL by now. In most applications, the URL is constructed by combining some static data with data from forms processed by the user. For example, the JavaScript code in listing 7 takes the value of the phone number field and uses it to construct URL.
Var request = false; try {request = new XMLHttpRequest ();} catch (trymicrosoft) {try {request = new ActiveXObject ("Msxml2.XMLHTTP");} catch (othermicrosoft) {try {request = new ActiveXObject ("Microsoft.XMLHTTP");} catch (failed) {request = false } if (! request) alert ("Error initializing XMLHttpRequest!"); function getCustomerInfo () {var phone= document.getElementById ("phone"). Value; var url = "/ cgi-local/lookupCustomer.php?phone=" + escape (phone);}
The code creates a new variable phone and assigns it the value of the form field whose ID is "phone".
Listing 8 shows the XHTML of this form, where you can see the phone field and its id property.
Listing 8. Break Neck Pizza form
Enter your phone number:
Your order will be sent to:
Type of your order:
Also note that when the user enters the phone number or changes the phone number, the getCustomerInfo () method shown in listing 8 is triggered. This method takes the phone number and constructs the URL string stored in the url variable. Remember, because the Ajax code is sandboxed, you can only connect to the same domain, and you don't actually need a domain name in URL. In this example, the script name is / cgi-local/lookupCustomer.php. Finally, the phone number is appended to the script as a GET parameter: "phone=" + escape (phone).
If you haven't seen the escape () method before, it is used to escape any characters that cannot be sent correctly in clear text. For example, the spaces in the phone number will be converted to the character% 20 so that these characters can be passed in URL.
You can add as many parameters as you need. For example, if you need to add another parameter, simply append it to the URL and separate it with the "and" (&) character [the first parameter is separated by a question mark (?) and the script name].
Open request
Once you have the URL to connect to, you can configure the request. You can do this with the open () method of the XMLHttpRequest object. This method has five parameters:
Request-type: the type of request sent. The typical value is GET or POST, but you can also send an HEAD request. Url: the URL to be connected. Asynch: true if you want to use an asynchronous connection, false otherwise. This parameter is optional and defaults to true. Username: if authentication is required, you can specify the user name here. There is no default value for this optional parameter. Password: if authentication is required, you can specify the password here. There is no default value for this optional parameter.
Is open () open? Internet developers don't agree on exactly what the open () method does. But it's not actually opening a request. If you monitor the network and data transfer between the XHTML/Ajax page and its connection script, you will not see any communication when the open () method is called.
The first three parameters are usually used. In fact, even if an asynchronous connection is required, the third parameter should be specified as "true". This is the default value, but it is easier to understand by insisting on explicitly specifying whether the request is asynchronous or synchronous.
Put these together, and you usually get the line of code shown in listing 9.
Listing 9. Open request
Function getCustomerInfo () {var phone= document.getElementById ("phone"). Value; var url = "/ cgi-local/lookupCustomer.php?phone=" + escape (phone); request.open ("GET", url, true);}
Once the URL is set up, the rest is simple. GET is sufficient for most requests (you'll see cases where you need to use POST in a later article), plus URL, and that's all you need to use the open () method.
Challenge asynchrony
In a later article in this series, I'll spend a lot of time writing and using asynchronous code, but you should understand why the last parameter of open () is so important. In a general request / response model, such as Web 1.0, the client (the browser or code running on the local machine) makes a request to the server. The request is synchronous; in other words, the client waits for a response from the server. When the client waits, at least you are notified in some form that you are waiting:
Hourglass (especially on Windows). A rotating ball (usually on a Mac machine). The application basically froze, and then the cursor changed after a while.
The asynchronous request does not wait for the server to respond. The application continues to run after the request is sent. Users can still enter data in the Web form or even leave the form. The server quietly responds to the request and tells the original requestor that the work is finished.
Send a request
Once configured with open (), you are ready to send the request.
Send () has only one parameter, which is the content to be sent. But before considering this approach, recall that the data was previously sent through the URL itself:
Var url = "/ cgi-local/lookupCustomer.php?phone=" + escape (phone)
Although you can send data using send (), you can also send data through URL itself. In fact, it is much easier to send data using URL in GET requests (about 80% in a typical Ajax application). If you need to send security information or XML, you may want to consider using send () to send content. If you don't need to pass data through send (), just pass null as an argument to the method.
Listing 10. Send a request
Function getCustomerInfo () {var phone= document.getElementById ("phone"). Value; var url = "/ cgi-local/lookupCustomer.php?phone=" + escape (phone); request.open ("GET", url, true); request.send (null);}
Specify callback method
Very little of what we do now is new, revolutionary, or asynchronous. It must be admitted that the small keyword "true" in the open () method establishes an asynchronous request. But other than that, this code is no different from programming in Java servlet and JSP, PHP, or Perl. So what's the biggest secret of Ajax and Web 2.0? The secret lies in onreadystatechange, a simple attribute of XMLHttpRequest.
First of all, be sure to understand the flow in this code (review listing 10 if necessary). Establish its request and then issue the request. In addition, because it is an asynchronous request, the JavaScript method (getCustomerInfo () in the example) does not wait for the server. So the code will continue to execute, that is, it will exit the method and return control to the form. The user can continue to enter information, and the application will not wait for the server.
This raises an interesting question: what happens after the server completes the request? The answer is nothing, at least for today's code! Obviously this won't work, so the server needs some instructions on what to do after it finishes processing the request sent to it through XMLHttpRequest.
Reference a function in JavaScript:
JavaScript is a weakly typed language that can refer to anything with variables. So if you declare a function updatePage (), JavaScript also treats the function name as a variable. In other words, the function can be referenced in the code with the variable name updatePage.
Listing 11. Set callback method
Function getCustomerInfo () {var phone= document.getElementById ("phone"). Value; var url = "/ cgi-local/lookupCustomer.php?phone=" + escape (phone); request.open ("GET", url, true); request.onreadystatechange = updatePage; request.send (null);}
Special attention should be paid to where this property is set in the code-- it is set before calling send (). This property must be set before sending the request so that the server can not view the property until the request has been answered. Now all that's left is to write the updatePage () method, which is the focus of the last section of this article.
Processing server responses
When the request is sent, the user happily uses the Web form (while the server is processing the request), and now the server has finished processing the request. The server looks at the onreadystatechange property to determine which method to call. In addition, you can think of your application as any other application, whether asynchronous or not. In other words, you don't have to take special action to write a method that responds to the server, just change the form to allow the user to access another URL or do whatever the server needs. In this section, we focus on the response to the server and the typical action of instantly changing part of the form that the user sees.
Back-harmonic Ajax
Now we've seen how to tell the server what to do when it's done: set the onreadystatechange property of the XMLHttpRequest object to the name of the function to run. In this way, the function is automatically called when the server finishes processing the request. Nor do you need to worry about any parameters of the function. Let's start with a simple method, as shown in listing 12.
Listing 12. Code for callback method
Var request = false; try {request = new XMLHttpRequest ();} catch (trymicrosoft) {try {request = new ActiveXObject ("Msxml2.XMLHTTP");} catch (othermicrosoft) {try {request = new ActiveXObject ("Microsoft.XMLHTTP");} catch (failed) {request = false;}} if (! request) alert ("Error initializing XMLHttpRequest!") Function getCustomerInfo () {var phone= document.getElementById ("phone"). Value; var url = "/ cgi-local/lookupCustomer.php?phone=" + escape (phone); request.open ("GET", url, true); request.onreadystatechange = updatePage; request.send (null);} function updatePage () {alert ("Server is done!");}
It just issues a few simple warnings to tell you when the server completes the task. Experiment with the code in your own web page and open it in a browser (if you want to see the XHTML in this example, see listing 8). Enter the phone number and leave the field, and you will see a pop-up warning window (shown in figure 3), but clicking OK appears again.
Depending on the browser, you will see two, three, or even four warnings before the form stops popping up. What's going on? It turns out that we haven't considered the HTTP ready state, which is an important part of the request / response cycle.
HTTP ready state
As mentioned earlier, the server looks for the method to be called in the onreadystatechange property of the XMLHttpRequest after completing the request. It's true, but it's not complete. In fact, it calls this method whenever the HTTP ready state changes. What does that mean? You must first understand the HTTP ready state.
The HTTP ready state indicates the state or situation of the request. It is used to determine whether the request has started, whether a response has been received, or whether the request / response model has been completed. It can also help determine whether it is safe to read the response text or data provided by the server. There are five ready states you need to know in your Ajax application:
0: the request is not issued (before calling open ()). 1: the request has been created but not issued (before calling send ()). 2: the request has been sent and is being processed (here you can usually get the content header from the response). 3: the request has been processed, and some data is usually available in the response, but the server has not yet completed the response. 4: the response is complete, you can access the server response and use it.
Like most cross-browser issues, the use of these ready states is inconsistent. You might expect the task ready state to range from 0 to 1, 2, 3, and then 4, but this is rarely the case. Some browsers never report 0 or 1 and start directly with 2, then 3 and 4. Other browsers report all status. Others report ready status 1 multiple times. As you saw in the previous section, the server called updatePage () multiple times, and each call brought up a warning box-- which may not be what you expected!
For Ajax programming, the only state that needs to be dealt with directly is ready state 4, which indicates that the server response is complete and that the response data is safe to use. Based on this, the first line in the callback method should look like listing 13.
Listing 13. Check ready statu
Function updatePage () {if (request.readyState = = 4) alert ("Server is done!");}
After modification, you can ensure that the processing of the server has been completed. Try to run the new version of the Ajax code and you will now see a warning message displayed only once, as expected.
HTTP status code
Although the code in listing 13 looks good, there is another problem-- what if the server responds to the request and finishes processing but reports an error? You know, server-side code should understand that it is called by Ajax, JSP, plain HTML forms, or other types of code, but can only report information using traditional Web-specific methods. In the Web world, HTTP code can handle all kinds of problems that can occur in a request.
For example, you must have encountered a situation where you typed an incorrect URL request and got a 404 error code, which indicates that the page does not exist. This is just one of the many error codes that a HTTP request can receive. 403 and 401, which indicate that the accessed data is protected or disabled, are also common. In either case, these error codes are obtained from the completed response. In other words, the server fulfilled the request (that is, the HTTP ready state is 4) but did not return the data expected by the client.
So in addition to the ready state, you also need to check the HTTP state. Our expected status code is 200, which indicates that everything is going well. If the ready state is 4 and the status code is 200, you can process the server's data, and that data should be the required data (not errors or other problematic information). So add a status check to the callback method, as shown in listing 14.
Listing 14. Check the HTTP status code
Function updatePage () {if (request.readyState = = 4) if (request.status = = 200) alert ("Server is done!");}
To add more robust error handling and avoid overly complex, you can add one or two status code checks. Take a look at the modified version of updatePage () in listing 15.
Listing 15. Add a little error checking
Function updatePage () {if (request.readyState = = 4) if (request.status = = 200) alert ("Server is done!"); else if (request.status = = 404) alert ("Request URL does not exist"); else alert ("Error: status code is" + request.status);}
Now change the URL in getCustomerInfo () to a non-existent URL and see what happens. You should see a warning that the required URL does not exist-- great! It is difficult to handle all error conditions, but this small change can cover 80% of the problems in a typical Web application.
Read response text
Now we can ensure that the request has been processed (through the ready state), the server has given a normal response (through the status code), and finally we can process the data returned by the server. The returned data is saved in the responseText property of the XMLHttpRequest object.
The text content in responseText, such as format and length, is deliberately ambiguous. This allows the server to set the text to anything. For example, one script might return comma-separated values, another would use pipe characters (that is, | characters) to separate values, and another might return long text strings. It is up to the server to decide where to go.
In the example used in this article, the server returns the customer's last order and customer address, separated by pipe characters. Then use the order and address to set the element values in the form, and listing 16 shows the code to update the display.
Listing 16. Processing server responses
Function updatePage () {if (request.readyState = = 4) {if (request.status = = 200) {var response = request.responseText.split ("|"); document.getElementById ("order"). Value = response [0]; document.getElementById ("address") [xss_clean] = response [1]. Replace (/\ nrequest.responseText.split g, ");} else alert (" status is "+ request.status) }}
First, you get the responseText and separate it from the pipe using the JavaScript split () method. The resulting array is put into response. The first value in the array-- the previous order-- is accessed with response [0] and is set to the value of the field whose ID is "order". The second value, response [1], the customer address, requires a little more processing. Because the lines in the address are separated by normal line delimiters ("\ n" characters), the code needs to be replaced by XHTML-style line delimiters. The replacement process is done using the replace () function and regular expressions. Finally, the modified text serves as the internal HTML in the HTML form div. The result is that the form is suddenly updated with customer information.
Before concluding this article, I'd like to introduce another important attribute of XMLHttpRequest, responseXML. If the server chooses to use a XML response, this property contains (as you may have guessed) a XML response. Dealing with XML responses is very different from dealing with plain text, involving parsing, document object Model (DOM), and other issues. XML will be introduced further in a later article. But because responseXML is usually discussed with responseText, it's worth mentioning here. ResponseText is sufficient for many simple Ajax applications, but you'll soon see that XML can also be handled well with Ajax applications.
At this point, the study on "what is the method of callback specified by JavaScript" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.