`
sunfengcheng
  • 浏览: 181048 次
  • 性别: 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
分享到:
评论

相关推荐

    JSF 2 0:Integrated Ajax Support

    jsf2.0 整合了ajax,这个是英文文档来的

    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,...

    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...

    VS2008-AJAX-Support

    WinVideo-HDI-VS08-AJAX-Support.zip

    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

    Yii 的登录流程

    Yii是一个全栈式的MVC框架,所谓全栈式指的是Yii框架本身实现了web开发中所要用到的所有功能,比如MVC,ORM(DAO/ActiveRecord), 全球化(I18N/L10N), 缓存(caching), 基于jQuery Ajax支持(jQuery-based AJAX support), ...

    dojo_ajax_support

    dojo的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 ...

    ajax4jsf中文教程

    a4j:support a4j:commandLink a4j:commandButton a4j:outputPanel a4j:actionparam a4j:status a4j:loadBundle a4j:mediaOutput 5. Ajax4jsf内建的换肤功能 6. 技术要求 支持的java版本 支持的 JavaServer...

    ExtAspNet_v2.3.2_dll

    ExtAspNet - ExtJS based ASP.NET Controls with Full AJAX Support ExtAspNet是一组专业的Asp.net控件库,拥有原生的AJAX支持和丰富的UI效果, 目标是创建没有ViewState,没有JavaScript,没有CSS,没有...

    The jQuery JavaScript Library

    The jQuery JavaScript Library Part I: Ajax Support

    ajax 4jsf用户指南中文版

    a4j:support a4j:commandLink a4j:commandButton a4j:outputPanel a4j:actionparam a4j:status a4j:loadBundle a4j:mediaOutput 5. Ajax4jsf内建的换肤功能 6. 技术要求 支持的 java版本 支持的 Java...

    jQuery的异步调用

    1.Overview of jQuery 2.Installation and documentation 3.Quick summary of jQuery selectors 4.Data centric Ajax: the $.ajax function 5.Content-centric Ajax: ...7.Comparing Ajax support to other libraries

    PHP5框架KissPHP.zip

    KISS is a PHP WEB Framework based on PHP5 OO Model! It has inbuild ORM module, multiple DB, MVC, Caching and Ajax support! 标签:KissPHP Web框架

    AJAX实现查询分页功能!!

    AJAX实现查询分页功能!!可以直接运行看看,不错的东西!!

    Yii框架登录流程分析

    Yii是一个全栈式的MVC框架,所谓全栈式指的是Yii框架本身实现了web开发中所要用到的所有功能,比如MVC,ORM(DAO/ActiveRecord), 全球化(I18N/L10N), 缓存(caching), 基于jQuery Ajax支持(jQuery-based AJAX support), ...

Global site tag (gtag.js) - Google Analytics