`
sunfengcheng
  • 浏览: 184310 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Ajax Support

阅读更多
[color=olive][size=medium][/size][color=brown]   

10.1. Ajax Support
In this section, we'll look at the three main classes that see most of the action in Prototype's Ajax code: Ajax.Request, Ajax.Updater, and Ajax.PeriodicalUpdaterall of which inherit from Ajax.Base. After that is the Ajax.Responders object, which handles global events related to Ajax calls.

10.1.1. Base Objects
The Ajax object serves as the root and namespace for Prototype's classes and methods that provide Ajax functionality:



activeRequestCount

The number of Ajax requests in progress



getTransport( )


Returns a new XMLHttpRequest object

Ajax.Base is used as the base class for other classes defined in the Ajax object. As such, these methods are available in Ajax.Request, Ajax.Updater, and Ajax.PeriodicalUpdater objects.



setOptions( options )


Sets the desired options for the Ajax operation. See "Ajax.Request options" later in this chapter.


引用

responseIsSuccess( )

TRue if the Ajax operation succeeded, and false otherwise.



引用
responseIsFailure( )


false if the Ajax operation succeeded, and TRue otherwise.

10.1.2. Ajax Requests
The Ajax.Request class (which inherits from Ajax.Base) encapsulates Ajax operations.



引用
initialize( url , options )


Creates one instance of this object that will create an XMLHttpRequest object for the given url, using the given options (which may include callbacks to handle the response; see the upcoming section "Ajax.Request options"). The onCreate event will be raised during the constructor call. Generally, only URLs from the same domain as the current page are allowed to be retrieved; see the discussion of "The Same-Origin Policy" in Chapter 8.



引用
request( url )


Called by the constructor; not typically called externally.



引用
evalJSON( )


Evaluates the content of an eventual X-JSON HTTP header present in the Ajax response. Not typically called externally.



引用
evalResponse( )


Evaluates the response body as JavaScript. Called internally if the response has a Content-type header of text/javascript. Not typically called externally.



引用
header( name )


Retrieves the contents of the HTTP header named name from the response (only available after the Ajax call is completed).



引用
onStateChange( )


Called internally when the readyState changes. See Table 10-2. Not typically called externally.



引用
respondToReadyState( readyState )


Called by the object when the readyState changes. See Table 10-1. Not typically called externally.



引用
setRequestHeaders( )


Assembles the HTTP header that will be sent during the HTTP request. Not typically called externally.



Events

An array of possible events/statuses reported during an Ajax operation. The list contains: Uninitialized, Loading, Loaded, Interactive, and Complete.



transport

The XMLHttpRequest object that carries the Ajax operation.



url

The URL targeted by the request.

10.1.2.1. Ajax.Request options
The options argument is an anonymous JavaScript object in literal notation. Any object can be passed as long as it has the expected properties, but it's common to create anonymous objects just for the Ajax calls (see Table 10-1).

Table 10-1. Ajax operations Property Description
method

A string with the HTTP method for the request. Defaults to post.
parameters

A object (like {pet:'monkey'}) or URL-formatted string (like "pet=monkey") with the list of values passed to the request. Defaults to empty.
encoding

A string representing the encoding of a request body. Defaults to UTF-8.
username

A string with the username to be used for HTTP authentication.
password

A string with the password to be used for HTTP authentication.
asynchronous

A Boolean indicating whether the Ajax call will be made asynchronously. Defaults to true.
contentType

A string specifying the Content-Type header that will be sent with the HTTP request. Defaults to application/x-www-form-urlencoded.
postBody

A string with the content passed to in the request's body in case of a HTTP POST or PUT. Defaults to undefined.
requestHeaders

A collection of HTTP headers to be passed with the request. Either an object (like {foo-header:'value 1', bar-header:'value 2'}) or an array with an even number of items (like ['foo-header', 'value 1', 'bar-header', 'value 2']). Defaults to undefined.
onLoading

Callback function to be called when the request's readyState reaches 1 (see Table 10-2). The function will receive two arguments: the XMLHttpRequest request object, and the evaluated X-JSON response HTTP header.
onLoaded

Callback function to be called when the request's readyState reaches 2 (see Table 10-2). The function will receive two arguments: the XMLHttpRequest request object, and the evaluated X-JSON response HTTP header.
onInteractive

Callback function to be called when the request's readyState reaches 3 (see Table 10-2). The function will receive two arguments: the XMLHttpRequest request object, and the evaluated X-JSON response HTTP header.
onComplete

Callback function to be called when the request's readyState reaches 4 (see Table 10-2). The function will receive two arguments: the XMLHttpRequest request object, and the evaluated X-JSON response HTTP header.
onSuccess

Callback function to be called when the request's readyState reaches 4 and the HTTP response status is in the 200 range. The function will receive two arguments: the XMLHttpRequest request object and the evaluated X-JSON response HTTP header.
onFailure

Callback function to be called when the request's readyState reaches 4 and the HTTP response status is not in the 200 range. The function will receive two arguments: the XMLHttpRequest request object and the evaluated X-JSON response HTTP header.
onException

Callback function to be called when an exceptional condition happens on the client side of the Ajax call, such as an invalid response or invalid arguments. The function will receive two arguments: the Ajax.Request request object and the exception object.




In addition to the callbacks available for the general response conditions (onSuccess, onFailure, etc.), callbacks can be created for specific HTTP response codes (404, 500, and so on) as well. See below for an example.

10.1.2.2. Examples
Create an Ajax request for a remote file, with options to specify the HTTP request method, and a callback to handle the response:

new Ajax.Request('/data.html', {
  method: 'get',
  onComplete: showResponse
});

// alert the returned value
function showResponse(request) {
  alert(request.responseText);
}

The callback could also be defined inline. For example, this is equivalent to the previous example (see Table 10-2):

new Ajax.Request(' /data.xml', {
  method: 'get',
  onComplete: function(request){ alert(request.responseText); }
});

Callbacks can be defined for specific HTTP response codes, as well:

new Ajax.Request(' /data.xml', {
  method: 'get',
  on404: function(request){ alert('Not found'); },
  on500: function(request){ alert('Server error'); }
});

Table 10-2. XMLHttpRequest readyState properties readyState Description Prototype callback
  Request object has not yet been created.  
0 (Uninitialized) Request object's open( ) method has not yet been called.  
1 (Loading) Request object's send( ) method has not yet been called. onLoading


2 (Loaded) The request has been initiated. onLoaded


3 (Interactive) The response is being received. onInteractive


  The response is ready and its status is in the 200 range. onSuccess


  The response is ready and its status is not in the 200 range. onFailure


4 (Complete) The response is ready. onComplete






10.1.3. Ajax Updaters
The Ajax.Updater class (which inherits from Ajax.Request) is used when the requested URL returns content that you want to inject directly in a specific element of your page.



initialize( container , url , options )

Creates an Ajax.Updater instance that will call url using the given options. The container argument can be the ID of an element, the element object itself, or an object with either or both of two properties: success, which is an element or ID that will be updated when the Ajax call succeeds, and failure, which is the element (or ID) that will be updated otherwise. The options argument provides the same options as Ajax.Request (see "Ajax.Request options," earlier in this chapter) and some options particular to updaters (see "Ajax.Updater options," next).



updateContent( )

Called internally when the response is received. It will update the appropriate element with the HTML or call the function passed in the insertion option. The function will be called with two arguments: the element to be updated and the response text. Not typically called externally.



containers

Contains two properties: success, which is the element to be updated when the request succeeds, and failure, which is the element to be updated otherwise.

10.1.3.1. Ajax.Updater options
In addition to the options described in the section "Ajax.Request options," Ajax.Updater classes can also take these options:

insertion

An Insertion class that will determine how the new content will be inserted. It can be Insertion.Before, Insertion.Top, Insertion.Bottom, or Insertion.After (see "Inserting Content"). Defaults to undefined.
evalScripts

A Boolean that determines whether <script> blocks will be evaluated when the response arrives, instead of inserted into the page. Defaults to undefined (false).




10.1.3.2. Examples
Replace the contents of a DIV with the contents of a remote file:

引用
// <div id="target">(To be replaced)</div>

new Ajax.Updater('target', '/data.html', {method: 'get'});

This next example is the same as above, but it updates the element only if the request was successful and alerts the user if not:

引用
//
<div id="target"></div>

new Ajax.Updater({success: 'target'}, '/data.html', {
  method: 'get', 
  onFailure: function(request) { alert('Sorry. There was an error.') }
});[/
quote]
10.1.4. Periodical Ajax Updaters
The Ajax.PeriodicalUpdater class repeatedly instantiates and uses an Ajax.Updater object to refresh an element on the page or to perform any of the other tasks the Ajax.Updater can perform.



initialize( container , url , options )

Creates an instance that will update container with the result of a request to url. container can be the id of an element, the element object itself, or an object with one or both of two properties: success, which is an element (or id) that will be updated when the request succeeds, and failure, which is an element (or id) that will be updated otherwise. The available properties of the options argument are detailed in the section below "Ajax.PeriodicalUpdater options."



start( )

Start performing the periodical tasks. Not typically called externally.



stop( )

Stop performing the periodical tasks. After stopping, the object will call the callback given in the onComplete option (if any).



updateComplete( )

Schedules the next refresh; called by the currently used Ajax.Updater after it completes the request. Not typically called externally.



onTimerEvent( )

Called internally when it is time for the next update. Not typically called externally.



container

An object that will be passed straight to the Ajax.Updater's constructor.



url

A string that will be passed straight to the Ajax.Updater's constructor.



frequency

Interval (not frequency) between refreshes, in seconds. Defaults to 2 seconds. This number will be multiplied by the current decay when invoking the Ajax.Updater object.



decay

A number that keeps the current decay level applied when re-executing the task.



updater

The most recently used Ajax.Updater object.



timer

The JavaScript timer being used to notify the object when it is time for the next refresh.

10.1.4.1. Ajax.PeriodicalUpdater options
In addition to the options described in the earlier sections "Ajax.Request options" and "Ajax.Updater options," Ajax.PeriodicalUpdater can also take these options:

decay

A number determining the progressive slowdown in an Ajax.PeriodicalUpdater object refresh rate when the received response is the same as the last one. For example, if the rate is 2 and one of the refreshes produces the same result as the previous one, the object will wait twice as much time for the next refresh. If it repeats again, the object will wait four times as much, and so on. Leave it undefined or use 1 to avoid the slowdown.
frequency

Interval (not frequency) between refreshes, in seconds. Applies only to Ajax.PeriodicalUpdater objects. Defaults to 2.




10.1.4.2. Example
引用
//
<div id="target"></div>

new Ajax.PeriodicalUpdater('target', '/data.html', {
  method: 'get', 
  frequency: 2
});[/
quote]10.1.5. Global Responders
The Ajax.Responders object maintains a list of callbacks that will be called when Ajax-related events occur, regardless of what object created them; for example, creating a global exception handler for Ajax operations. If you have code that should always be executed for a particular event, regardless of which Ajax call caused it to happen, then you can use the Ajax.Responders object.



register( responderToAdd )

The object passed in the responderToAdd argument should contain methods named like the Ajax events (e.g., onCreate, onComplete, onException). When the corresponding event occurs, all the registered objects that contain a method with the appropriate name will have that method called.



unregister( responderToRemove )

The object passed in the responderToRemove argument will be removed from the list of registered objects.



dispatch( callback , request , transport , json )

Runs through the list of registered objects looking for the ones that have the method determined in callback. Then each of these methods is called passing request, transport, and json. If the Ajax response contains an X-JSON HTTP header with some JSON content, then it will be evaluated and passed in the json argument. If the event is onException, the transport argument will have the exception instead and json will not be passed.



responders

An array of objects registered for Ajax events notifications.

In addition to the methods listed here, Ajax.Responders is also extended by the Enumerable methods.

10.1.5.1. Example
Suppose you want to show some visual indication that an Ajax call is in progress, such as a spinning icon. You can use two global event handlers to help you, one to show the icon when the first call starts and another one to hide the icon when the last one finishes.

引用
// <img src="spinner.gif" id="spinner" style="display: none">

Ajax.Responders.register({
  onCreate: function(  ){
    $('spinner').show(  );
  },
  onComplete: function(  ) {
    if(Ajax.activeRequestCount == 0)
      $('spinner').hide(  );
  }
});[/
quote]

    [/color][/color]
4
2
分享到:
评论

相关推荐

    Struts 2 and Ajax

    因此,Struts 2其中的一个重要的功能(Feature)就是“First-class AJAX support - Add interactivity and flexibility with AJAX tags that look and feel just like standard Struts tags(大意:一流的AJAX支持...

    struts2.0_Ajax

    因此,Struts 2其中的一个重要的功能(Feature)就是“First-class AJAX support - Add interactivity and flexibility with AJAX tags that look and feel just like standard Struts tags(大意:一流的AJAX支持...

    jquery1.9.1 支持低版本ajax (ajax前jQuery.support.cors=true )

    jquery1.9.1 支持低版本ajax (ajax前jQuery.support.cors=true )

    TreeGrid控件及Demo源码

    Support Ajax Support Postback Support Callback Support Event -- Select Edit Update Delete Support DataBind like TreeView Support DataBind like GirdView Support ASP.net 2.0, but this demo is 3.5,...

    ajax in prpc

    - **Higher IO (AJAX) Abstraction:** One of the most significant features of Dojo is its AJAX support. It provides a high-level abstraction over AJAX calls, making it simpler to perform asynchronous ...

    VS2008-AJAX-Support

    【VS2008-AJAX-Support】是关于Visual Studio 2008中对AJAX技术的支持和应用的专题。Visual Studio 2008(VS2008)是微软推出的一款强大的集成开发环境(IDE),它极大地提高了开发者的工作效率,尤其在Web应用程序...

    ExtAspNet_v2.1.5_dll

    ExtAspNet is a set of professional Asp.net controls with native AJAX support and rich UI effect which aim at No JavaScript, No CSS, No UpdatePanel and No WebServices. Support Browsers: IE 7.0+, Fire...

    Yii,PHP FRAMEWORK ORM

    他几乎拥有了所有的特性,包括MVC, DAO/ActiveRecord, I18N/L10N, caching, jQuery-based AJAX support, 用户认证和基于角色的访问控制, 脚手架, 输入验证, 部件, 事件, 主题化以及Web services等. 用严格的OOP编码...

    Ajax4jsf User Guide

    Ajax4jsf is an open source framework that adds AJAX ... Ajax4jsf rich components with built-in AJAX support and a highly customizable look-and-feel can be easily incorporated into JSF applications

    dhtmlxWindows.rar_dhtmlxcontainer.js_floating

    【Ajax Support】表示该库还集成了Ajax技术。Ajax(异步JavaScript和XML)是一种在无需刷新整个网页的情况下更新部分网页的技术。在dhtmlxWindows中,这意味着窗口内容可以通过Ajax请求动态加载,这样可以提高页面...

    dojo_ajax_support

    ### Dojo Toolkit与Ajax支持详解 #### 一、概述 **Dojo** 是一个功能强大的JavaScript库,旨在简化客户端Web应用程序的开发。它提供了一系列工具和技术来帮助开发者创建高性能、可扩展的应用程序。其中,Dojo对...

    prototype 1.4 开发者手册(中文PDF)

    ##### 4.1 AJAX Support Prototype 提供了一套完整的 AJAX 工具集,包括 `Ajax.Request` 方法,用于发起异步请求并处理响应数据: ```javascript var request = new Ajax.Request('/some-url', { method: 'get', ...

    《 jQuery实战.pdf》高清下载

    4. AJAX支持(AJAX Support):jQuery对AJAX操作提供了统一的接口,可以方便地处理各种服务器响应,如JSON、XML等格式数据。 5. 插件机制(Plugins):由于jQuery的开放性,它有一个庞大的插件社区,这些插件可以...

    Asp.net 2.0模块四

    C23 - "Asp.net 2.0 Ajax Support" 在Asp.NET 2.0中,微软引入了Atlas(后来成为AjaxControlToolkit)来支持Ajax无刷新技术。这使得开发者能够创建更流畅、响应更快的用户体验,无需完全刷新页面即可更新部分内容。...

    Practical Apache Struts2 Web 2.0 Projects

    Yet the latest version 2 release takes developers’ capabilities to the next level, having integrated Ajax support, the ability to easily integration with the Spring framework, and the ability to ...

    ASP.NET 2.0 Instant Results

    AJAX Support 虽然ASP.NET 2.0本身不直接支持AJAX,但微软随后推出了ASP.NET AJAX框架,使得开发者能够更轻松地在ASP.NET应用程序中集成AJAX技术,实现更丰富的用户体验。 ### 总结 《ASP.NET 2.0 Instant ...

    ZKoss jar包

    6. **AJAX Support**: ZK通过内置的AJAX技术实现局部更新,提升Web应用的响应速度和用户体验,而无需全页面刷新。 7. **Internationalization and Localization**: ZK支持国际化和本地化,开发者可以轻松地为不同...

    Telerik kendoui 2013.1.514

    8. **Ajax支持(Ajax Support)**:Kendo UI控件与服务器的通信通常基于Ajax,使得页面刷新最小化,提高应用性能。 9. **主题(Themes)**:Kendo UI提供了多种预设主题,2013.1.514可能对主题系统进行了优化,方便...

    JavaServer Faces 2.0, The Complete Reference源码

    6. **Ajax Support**:JSF 2.0增强了Ajax功能,提供了`&lt;f:ajax&gt;`标签,使得异步更新部分视图变得更加简单,同时也支持自定义Ajax行为。 7. **Facelet Composability**:允许在Facelets页面中嵌入其他Facelets,实现...

Global site tag (gtag.js) - Google Analytics