`
wpf_0508
  • 浏览: 12433 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

ajaxAnyWhere开发学习

阅读更多

Dependent List Example

Let us make a dependent list example with AjaxAnywhere.

We will take as a starting point a traditional JSP solution. Then we will integrate it with AjaxAnywhere. 

To feel and compare the page behavior with and wothout AjaxAnywhere, click on this Online Demo 

<%@ page pageEncoding="UTF-8" import="java.util.*"%>
<%  // some unimportant code here
    String currentLanguage = request.getParameter("language");
    if (currentLanguage==null)
        currentLanguage="en";

    Locale[] availableLocales = Locale.getAvailableLocales();
    Map languagesDisplay = new TreeMap();
    Map countries = new TreeMap();

    for (int i = 0; i < availableLocales.length; i++) {
        Locale loc= availableLocales[i];
        languagesDisplay.put(loc.getLanguage(), loc.getDisplayLanguage(Locale.ENGLISH));
        if (loc.getDisplayCountry(Locale.ENGLISH).length()>0 
            && loc.getLanguage().equals(currentLanguage))
            countries.put(loc.getCountry(), loc.getDisplayCountry(Locale.ENGLISH));
    }
%>

Without AjaxAnywhere <br>
<%@ include file="/locales_counter.jsp"%>

<form method="POST" name=main>

    <select size="10" name="language" onchange="this.form.submit()">
        <%@ include file="/locales_options_lang.jsp"%>
    </select>


    <select size="10" name="country" >
        <%@ include file="/locales_options_countries.jsp.jsp"%>
    </select>
</form>


The first list contains all languages available in the JVM. The second list contains countries that use the selected language. As a new item of the first list is selected, the page gets reloaded refreshed, updating the second list with the countries that uses the selected language. 

The following code shows how easily we can make this page use AJAX.


<%@ page pageEncoding="UTF-8" import="java.util.*"%>
<%@ page import="org.ajaxanywhere.AAUtils"%>
<%@ taglib uri="http://ajaxanywhere.sourceforge.net/" prefix="aa" %>

<%
    String currentLanguage = request.getParameter("language");
    if (currentLanguage==null)
        currentLanguage="en";

    Locale[] availableLocales = Locale.getAvailableLocales();
    Map languagesDisplay = new TreeMap();
    Map countries = new TreeMap();

    for (int i = 0; i < availableLocales.length; i++) {
        Locale loc= availableLocales[i];
        languagesDisplay.put(loc.getLanguage(), loc.getDisplayLanguage(Locale.ENGLISH));
        if (loc.getDisplayCountry(Locale.ENGLISH).length()>0 
            && loc.getLanguage().equals(currentLanguage))
            countries.put(loc.getCountry(), loc.getDisplayCountry(Locale.ENGLISH));
    }


// this code does not have to be placed inside a JSP page. It can (should)
// be executed inside your Controller, if you use an MVC famework. For Struts, for example,
// this code goes to an Action class.

    if (AAUtils.isAjaxRequest(request)){
        AAUtils.addZones(request, "countriesList");
    }

%>

<script src="aa/aa.js"></script><script>ajaxAnywhere.formName = "main";</script>

With AjaxAnywhere <br>
<%@ include file="/locales_counter.jsp"%>

<form method="POST" name=main>

<!-- Here the form does not have action attribute. 
This means that the form is submitted to
the original URL, this JSP page in our case.

However, your application may submit to a different URL.

Also, you application may use GET, instead of POST, download AjaxAnywhere Demo Application for more examples.
-->


    <select size="10" name="language" onchange="ajaxAnywhere.submitAJAX();">
        <%@ include file="/locales_options_lang.jsp"%>
    </select>

<aa:zone name="countriesList">

    <select size="10" name="country" >
        <%@ include file="/locales_options_countries.jsp.jsp"%>
    </select>

</aa:zone>


</form>




Do not forget that AAFilter must be properly mapped in web.xml (see also : Installation )
    <filter>
        <filter-name>AjaxAnywhere</filter-name>
        <filter-class>org.ajaxanywhere.AAFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>AjaxAnywhere</filter-name>
        <url-pattern>*.jsp</url-pattern>
    </filter-mapping>


Now we will take a close look at each modification:
  • First of all we use aa:zone custom tag to mark a zone that needs to be refreshed.
  • Then we include JavaScript file and assign the form name to a property of AjaxAnywhere default instance. We also modify onchange attribute of the first list.
  • Finally, on the server side we use AAUtil class to indicate what zone is to be refreshed. As the zone name was already known before submitting the request, we could also have implemented this logic on the client-side instead:
    ajaxAnywhere.getZonesToReload = function() {
    	return "countriesList";
    }
    
More examples are availble inside the AjawAnywhere DEMO Application, which is available for download. Detailed documentation will be shortly available. Stay tuned.
 
© 2005-2007 AjaxAnywhere Project
 
 

 

 

Class AjaxAnywhere

Object
   |
   +--AjaxAnywhere

class AjaxAnywhere

Defined in aa.js


Field Summary
 Object delayBeforeContentUpdate 
          
 Object delayInMillis 
          
 Object formName 
          
 Object id 
          
 Object notSupported 
          
 Object req 
          
 Object substitutedSubmitButtons 
          Stores substitutes SubmitButton names in to redo sustitution if a button was eventually inside a refresh zone.
 Object substitutedSubmitButtonsInfo 
          
<static>  Object defaultInstanceName 
          

 

Constructor Summary
AjaxAnywhere () 
           

 

Method Summary
 void bindById() 
           Binds this instance to window object using "AjaxAnywhere."+this.id as a key.
 void callback() 
           A callback.
 void dropPreviousRequest() 
           Used internally by AjaxAnywhere.
 Object findForm() 
           Returns a Form object that corresponds to formName property of this AjaxAnywhere class instance.
 Object getAJAX(url, zonesToRefresh) 
           sends a GET request to the server.
 Object getDelayTime() 
           Returns the delay period in milliseconds.
 Object getGlobalScriptsDeclarationsList(script) 
           If the HTML received in responce to AJAX request contains JavaScript that defines new functions/variables, they must be propagated to the proper context.
 Object getZonesToReaload(url, submitButton) 
           depreceted : wrond spelling : Reaload will be removed in later versions
 Object getZonesToReload(url, submitButton) 
           This function should be overridden by AjaxAnywhere user to implement client-side determination of zones to reload.
 void handleException(type, details) 
           If an exception is throws on the server-side during AJAX request, it will be processed by this function.
 void handleHttpErrorCode(code) 
           If an HTTP Error code returned during AJAX request, it will be processed by this function.
 void handlePrevousRequestAborted() 
           Override it if you need.
 void hideLoadingMessage() 
           Default sample loading message hide function.
 Object isDelayBeforeLoad() 
           Returns the current delay behavior.
 Object isFormSubmitByAjax() 
           Override this function if you use AjaxAnywhere.substituteFormSubmitFunction() to dynamically inform AjaxAnywhere of the method you want to use for the form submission.
 void onAfterResponseProcessing() 
           Override this method to implement a custom action
 void onBeforeResponseProcessing() 
           Override this method to implement a custom action
 Object onGetAjaxNotSupported(url) 
           Provides a default implementation from graceful degradation for getAJAX() calls location.href=url if XMLHttpRequest is unavailable, reloading the entire page .
 void onRequestSent() 
           Override this method to implement a custom action
 Object onSubmitAjaxNotSupported(additionalPostData, submitButton) 
           Provides a default implementation from graceful degradation for submitAJAX() calls form.submit() if XMLHttpRequest is unavailable, reloading the entire page
 Object preparePostData(submitButton) 
           Internally used to prepare Post data.
 void setDelayBeforeLoad(isDelay) 
           Some browsers (notably IE) do not load images from thier cache when content is updated using innerHTML.
 void setDelayTime(delayMillis) 
           Sets the delay period in milliseconds.
 void showLoadingMessage() 
           Default sample loading message show function.
 Object submitAJAX(additionalPostData, submitButton) 
           This function is used to submit all form fields by AJAX request to the server.
 void substituteFormSubmitFunction() 
           This function is used to facilitatte AjaxAnywhere integration with existing projects/frameworks.
 void substituteSubmitButtonsBehavior(keepExistingOnClickHandler, elements) 
           Substitutes the default behavior of <input type=submit|image> to submit the form via AjaxAnywhere.
<static> Object findInstance(id) 
           Finds an instance by id.

Field Detail

 

delayBeforeContentUpdate

Object delayBeforeContentUpdate

delayInMillis

Object delayInMillis

formName

Object formName

id

Object id

notSupported

Object notSupported

req

Object req

substitutedSubmitButtons

Object substitutedSubmitButtons
    Stores substitutes SubmitButton names in to redo sustitution if a button was eventually inside a refresh zone.

substitutedSubmitButtonsInfo

Object substitutedSubmitButtonsInfo

defaultInstanceName

<static> Object defaultInstanceName

Constructor Detail

AjaxAnywhere

AjaxAnywhere()

Method Detail

bindById

void bindById()
    Binds this instance to window object using "AjaxAnywhere."+this.id as a key.

callback

void callback()
    A callback. internally used

dropPreviousRequest

void dropPreviousRequest()
    Used internally by AjaxAnywhere. Aborts previous request if not completed.

findForm

Object findForm()
    Returns a Form object that corresponds to formName property of this AjaxAnywhere class instance.

getAJAX

Object getAJAX(url, zonesToRefresh)
    sends a GET request to the server.

getDelayTime

Object getDelayTime()
    Returns the delay period in milliseconds.

getGlobalScriptsDeclarationsList

Object getGlobalScriptsDeclarationsList(script)
    If the HTML received in responce to AJAX request contains JavaScript that defines new functions/variables, they must be propagated to the proper context. Override this method to return the Array of function/variable names.

getZonesToReaload

Object getZonesToReaload(url, submitButton)
    depreceted : wrond spelling : Reaload will be removed in later versions

getZonesToReload

Object getZonesToReload(url, submitButton)
    This function should be overridden by AjaxAnywhere user to implement client-side determination of zones to reload. If the form is submited with <input type=submit|image>, submitButton is a reference to the DHTML object. Otherwise - undefined.

handleException

void handleException(type, details)
    If an exception is throws on the server-side during AJAX request, it will be processed by this function. The default implementation is alert(stackTrace); Override it if you need.

handleHttpErrorCode

void handleHttpErrorCode(code)
    If an HTTP Error code returned during AJAX request, it will be processed by this function. The default implementation is alert(code); Override it if you need.

handlePrevousRequestAborted

void handlePrevousRequestAborted()
    Override it if you need.

hideLoadingMessage

void hideLoadingMessage()
    Default sample loading message hide function. Overrride it if you like.

isDelayBeforeLoad

Object isDelayBeforeLoad()
    Returns the current delay behavior.

isFormSubmitByAjax

Object isFormSubmitByAjax()
    Override this function if you use AjaxAnywhere.substituteFormSubmitFunction() to dynamically inform AjaxAnywhere of the method you want to use for the form submission.

onAfterResponseProcessing

void onAfterResponseProcessing()
    Override this method to implement a custom action

onBeforeResponseProcessing

void onBeforeResponseProcessing()
    Override this method to implement a custom action

onGetAjaxNotSupported

Object onGetAjaxNotSupported(url)
    Provides a default implementation from graceful degradation for getAJAX() calls location.href=url if XMLHttpRequest is unavailable, reloading the entire page .

onRequestSent

void onRequestSent()
    Override this method to implement a custom action

onSubmitAjaxNotSupported

Object onSubmitAjaxNotSupported(additionalPostData, submitButton)
    Provides a default implementation from graceful degradation for submitAJAX() calls form.submit() if XMLHttpRequest is unavailable, reloading the entire page

preparePostData

Object preparePostData(submitButton)
    Internally used to prepare Post data. If the form is submited with <input type=submit|image>, submitButton is a reference to the DHTML object. Otherwise - undefined.

setDelayBeforeLoad

void setDelayBeforeLoad(isDelay)
    Some browsers (notably IE) do not load images from thier cache when content is updated using innerHTML. As a result, each image is re-requested from the server even though the image exists in the cache. To work around this issue, AjaxAnywhere preloads images present in the new content and intrduces a brief dely (default of 100 milleseconds) before calling innerHTML. See http://support.microsoft.com/default.aspx?scid=kb;en-us;319546 for further details. This function can be used to change this behaviour.

Parameters:boolean

       - ) isDelay

setDelayTime

void setDelayTime(delayMillis)
    Sets the delay period in milliseconds. The default delay is 100 milliseconds.

Parameters:int

       - ) delayMillis

showLoadingMessage

void showLoadingMessage()
    Default sample loading message show function. Overrride it if you like.

submitAJAX

Object submitAJAX(additionalPostData, submitButton)
    This function is used to submit all form fields by AJAX request to the server. If the form is submited with <input type=submit|image>, submitButton should be a reference to the DHTML object. Otherwise - undefined.

substituteFormSubmitFunction

void substituteFormSubmitFunction()
    This function is used to facilitatte AjaxAnywhere integration with existing projects/frameworks. It substitutes default Form.sumbit(). The new implementation calls AjaxAnywhere.isFormSubmitByAjax() function to find out if the form should be submitted in traditional way or by AjaxAnywhere.

substituteSubmitButtonsBehavior

void substituteSubmitButtonsBehavior(keepExistingOnClickHandler, elements)
    Substitutes the default behavior of <input type=submit|image> to submit the form via AjaxAnywhere.

Parameters:indicates

         - if existing onClick handlers should be preserved. If keepExistingOnClickHandler==true, Existing handler will be called first if it returns false, or if event.returnValue==false, AjaxAnywhere will not continue form submission. If keepExistingOnClickHandler==false or undefines, existing onClick event handlers will be replaced.

list

       - of submitButtons and submitImages names. If the parameter is omitted or undefined, all elements will be processed

findInstance

<static> Object findInstance(id)
    Finds an instance by id.

 

Documentation generated by JSDoc on Thu Dec 7 18:03:06 2006
 
 
 
分享到:
评论
1 楼 wpf_0508 2016-07-26  
ajaxAnywhere使用步骤
标签: ajaxinputfilteractionfunctionbean
2012-03-08 16:16 2062人阅读 评论(0) 收藏 举报
版权声明:本文为博主原创文章,未经博主允许不得转载。

1、  把 ajaxanywhere-1.2-RC2.jar 压缩包复制到  \工程名\WebRoot\WEB-INF\lib 目录下。

2、  把 ajaxanywhere.tld 文件复制到 \工程名\WebRoot\WEB-INF 目录下。

3、  把 js 文件夹复制到  \工程名\WebRoot  目录下。

4、把 log4j-1.2.11.jar 加到WebRoot\WEB-INF\lib 目录下

5、在 web.xml 中添加 ajax 的配置

    <!-- Ajax配置开始,带编码转换(包括ajax提交的编码) -->

    <filter>

        <filter-name>AjaxAnywhere</filter-name>

        <filter-class>org.ajaxanywhere.AAFilter</filter-class>

        <init-param>

            <param-name>ShowInfo</param-name>

            <param-value>false</param-value>

        </init-param>

        <init-param>

            <param-name>encoding</param-name><!-- 普通提交方式编码 -->

            <param-value>GB2312</param-value>

        </init-param>

        <init-param>

            <param-name>ajaxencoding</param-name><!-- AJAX提交方式编码 -->

            <param-value>GB2312</param-value>

        </init-param>

    </filter>

    <filter-mapping>

        <filter-name>AjaxAnywhere</filter-name>

        <url-pattern>/*</url-pattern>

    </filter-mapping>

    <!-- Ajax配置结束 -->

6、新建 login.jsp 文件,添加 ajax 标签
<%@ page language="java" pageEncoding="gbk"%>



<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>

<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>

<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>

<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>



<%@ taglib uri="/WEB-INF/ajaxanywhere.tld" prefix="ajax"%>



7、导入 ajax 文件
<!--  select.js 主要有:onSelect() 与 onSelectAll()方法-->

<script src="js/select.js" type="text/javascript"></script>

<!--  Ajax JS 与ajvaAnywhere 组件包结合使用 必须-->

<script src="js/ajax.js" type="text/javascript"></script>



8、定义刷新热区
   <label><ajax:zone name="AdminZone"><font color="red">${requestScope.IsAdmin }</font></ajax:zone></label>

9、定义触发事件:<input name="aname" type="text" class="input_normal" id="aname"  onblur="checkuser()">
可以是: 失去焦点、点击、双击

10、编写脚本方法:

<script type="text/javascript">

//ajax 判断用户是否存在

    function checkuser(){

        var username=document.loginForm.aname.value;

if(username!=""){         //ajaxAnywhere.getAJAX("adminAction.do?methods=isAdmin&aname="+username);

          document.loginForm.action="login.do?methods=isAdmin";

          ajaxAnywhere.formName="loginForm";

          ajaxAnywhere.submitAJAX();

        

        }

    }

</script>

11、建立相应的 form 和 action

    /**

     * 可以用Ajax来判断用户名是否存在(登陆验证)

     * @param mapping

     * @param form

     * @param request

     * @param response

     * @return

     */

    public ActionForward isAdmin(ActionMapping mapping, ActionForm form,

            HttpServletRequest request, HttpServletResponse response){

      

        LoginForm loginForm = (LoginForm) form;

        // 处理刷新区域

        if (AAUtils.isAjaxRequest(request)) {

            /**下面的AdminExistZone 为热区的名字,即在jsp中<aa:zone name="AdminExistZone">...</aa:zone>中的name属性的值*/

            AAUtils.addZonesToRefresh(request, "AdminZone");  

        }

        if(loginForm.getAname().equals("xx")){

            request.setAttribute("IsAdmin", "用户名存在!");        

        }else{

            request.setAttribute("IsAdmin", "该用户名不存在!");    

        }

      

        return new ActionForward("/login.jsp");

    }

12、修改 struts-config.xml 文件的配置

相关推荐

Global site tag (gtag.js) - Google Analytics