Introduction to prototype Ajax

Source: Internet
Author: User
Introduction to prototype Ajax [translation completed]

Original article: http://www.prototypejs.org/learn/introduction-to-ajax]
Www.ruby-china.cn webmaster

The prototype framework provides very easy and interesting methods to handle Ajax calls. It is also secure for browsers.
. In addition to simple requests, this module (Ajax in prototype) can also intelligently process requests returned from the server.
JavascriptCodeAnd provides a secondary class for continuous round robin.

Ajax functions are included in global Ajax objects. The transport used for Ajax requests is XMLHttpRequest,
It is an abstract result of security for different browsers from the user's perspective. The real request is through creating Ajax.
The instance of the request object. Copy the content to the clipboard code:
New Ajax. Request ('/some_url', {method: 'get'}); the first parameter is the request address, and the second parameter is
Optional hash value. The method option specifies the HTTP request method to be used. The default value is post.

Remember, for security reasons (that is, to prevent cross-site scripting attacks) Ajax requests can only be used and contain this Ajax request
Find the same protocol, host, and port on the page. Some browsers allow arbitrary URLs, but you can leave them alone.

Ajax response callback

Ajax requests are asynchronous by default, which means that you must have a callback function to process the returned data. Callback Method
Send an optional hash when initiating a request. Copy the content to the clipboard code:

New Ajax. request ('/some_url', {method: 'get', onsuccess: function (Transport) {var response = transport. responsetext | "no response text"; alert ("success! \ N "+ response) ;}, onfailure: function () {alert ('something wrong ...')}});

The two callback functions pass the hash value to indicate the Success and Failure warnings respectively. Onsuccess and
Onfailure is called Based on the returned status. The first parameter is the native XMLHTTPRequest object.
Use the responsetext and responsexml attributes respectively.

You can define both callbacks, or either one or none. This is up to you. Other call back functions that can be used
And:

 
Onuninitialized, onloading, onloaded, oninteractive, oncomplete andonexception.

They all have a relationship with a certain state of the XMLHttpRequest transmission, except that when exceptions occur during the delivery of other callbacks
Except for onexception.

The onxxx callback is also available. Here, XXX is the returned status of HTTP, such as 200 or 404. Note:
Yes. If you use this method, your onsuccess and onfailure will not be called. Because onxxx has higher performance
First, because it means that you know what you are doing.

The onuninitialized, onloading, onloaded, and oninteractive callback functions are not completely
All browsers are implemented. Avoid using them.

Parameters and HTTP methods

You can pass request parameters like a parameter property. Copy the content to the clipboard code: New Ajax. request ('/some_url', {method: 'get', parameters: {company: 'example ', limit: 12 }}); the parameter is sent in the format of Company = example & limit = 12. You can use any of the get/post methods. However, it should be noted that the GET request should not be directed to the resulting data changes. The browser rarely caches POST requests, but it often caches GET requests. An important application of parameter attributes is to use Ajax requests to send a form content. prototype has provided you with a help method called form. serialize: copy the content to the clipboard code: New Ajax. request ('/some_url', {parameters: $ ('Id _ of_form_element '). serialize (true)}); if you need to send a custom HTTP Request Header, you can use the requestheaders item. You only need to pass in the name-value pair as a hash or a flat array. For example, ['x-custom-1 ', 'value', 'x-custom-2', 'other value']. for some reason, if you have to post a custom post body (No parameter from the parameter item) request, there is a postbody item for this purpose. Note that if you use postbody, all parameters you pass in will not be sent because postbody has a higher priority. In this case, you should be sober. Evaluate JavaScript return values sometimes apply Program Send JavaScript code as a response. If the returned contenty-type is the same as the MIME type of JavaScript, prototype will automatically return the code eval. If you do not need it, you do not need to explicitly process the response. It is also possible that this response is a X-JSON header, then his content will be parsed, save the establishment of an object concurrency to these callback functions, as a second parameter: copy the content to the clipboard code: New Ajax. request ('/some_url', {method: 'get', onsuccess: function (transport, JSON) {alert (JSON? Object. Inspect (JSON): "No JSON object") ;}}); you can use this function to retrieve important data to avoid the loss of XML parsing. JSON is faster (of course lighter) than XML ). The global responder has an object called Ajax. Responders every Ajax request. You can use it to register the callback function in any Ajax. triggered when the Request status occurs: copy the content to the clipboard code: Ajax. responders. register ({oncreate: function () {alert ('A request has been initialized! ') ;}, Oncomplete: function () {alert ('A request completed') ;}}); each callback that matches the transmission status of XMLHttpRequest can be placed here, and the previous oncreate. Global tracking requests like this are useful in many aspects: You can record them for debugging or throw an exception to solve possible connection problems. Developers who use Ajax. Updater to dynamically update your page often want to use Ajax requests to receive HTML fragments to update part of the document. The oncomplete callback through Ajax. Request is quite easy, but it will become easier if Ajax. Update is used. Suppose your HTML document contains the following code: copy the content to the clipboard: <H2> our fantastic products </H2> <Div id = "Products"> (fetching product list ...) </div> the 'products' container is empty. You want to put the HTML return value of the Ajax response here. No problem: copy the content to the clipboard code: New Ajax. updater ('products', '/some_url', {method: 'get'}); this is all, no other work. The variables are the same as those of Ajax. Request. In addition to the first position, a receiving element is added. Prototype uses element. Update () to update the response to the container. If your HTML contains some scripts, they will be filtered out by default. to execute your script, you must upload the true value to the evalscripts option. What if an error occurs and the server returns an error message instead of HTML? Generally, you do not want to insert errors to the content you need. Fortunately, prototype provides a solution: You are now passing in this form in the first parameter {success: 'products', failure: 'errors '} indicates the hash value of two different containers, not the original one. If it succeeds, the content will be placed on the success container, and the error will be placed on the Failure container. By using these features, your interface will become more user-friendly. You may not want to overwrite the content in the current container, but want to add the new HTML to the beginning or end. That's good. You can do it all. Just pass the object to be inserted as an insert parameter to Ajax: copy the content to the clipboard code: New Ajax. updater ('products', '/some_url', {method: 'get', insertion: insertion. top}); Ajax. updater inserts the returned HTML in the 'products' element of the container using the given object. Beautiful techniques! Using ajax. periodicalupdater to automatically execute a request you find Ajax. Updater is cool, but you still want to regularly execute it to retrieve data from the server? This is also available in the prototype framework. This is Ajax. periodicalupdater, which basically runs Ajax. Updater regularly. Copy the content to the clipboard code: New Ajax. periodicalupdater ('products', '/some_url', {method: 'get', insertion: insertion. top, frequency: 1, decay: 2}); two new parameters are frequency and recession. The frequency is the request generation interval, expressed in seconds. Here it is 1 second, indicating that AJAX requests are made every minute. The default frequency is 2 seconds. Our users may be very happy to have such a good response program, but our server may be under a lot of pressure if users have been using the browser for a long time. This is why the decay option exists. This is a factor. Through this factor, the frequency is doubled every time the same returned content is obtained. The first time may be 1 second, then 2 seconds, then 4 seconds, and then 8. Of course, if the server always returns different data, decay will not work. This factor only works if your content remains unchanged and the returned data is basically the same. Lowering the frequency can significantly reduce the burden on the server because useless requests are reduced. You can use this factor to monitor the server load, or you can pass in 1 to completely turn it off (1 is the default value) or omit it.

Continue
Learn more about Ajax. Request, Ajax. Updater, and Ajax projects.

2008-path to work for fresh graduates

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.