`
wpf_0508
  • 浏览: 13522 次
  • 性别: 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 文件的配置

相关推荐

    AjaxAnywhere

    在**源码**方面,AjaxAnywhere可能是开源的,允许开发人员查看和修改其内部工作原理。这为开发者提供了学习和定制的可能性,可以根据项目需求进行扩展或调整。通过查看源码,我们可以了解它是如何处理Ajax请求、响应...

    ajaxAnyWhere所需jar包及实例

    **AjaxAnyWhere** 是一个JavaScript库...学习和使用AjaxAnyWhere,不仅可以提升Web应用的交互性和响应速度,还能让你的代码更简洁,提高开发效率。通过深入理解这个库,你可以构建出更加高效和用户友好的Web应用程序。

    ajaxanywhere 使用

    AjaxAnywhere作为一个开源项目,其源码可供开发者深入学习和自定义。通过研究源码,可以理解其内部机制,优化性能或添加特定功能。此外,作为一款工具,AjaxAnywhere可能提供了调试工具、插件支持,帮助开发者更好地...

    ajaxanywhere 实例源码 myeclipse可以直接打开

    AjaxAnywhere是一款强大的JavaScript库,专为开发人员提供方便的AJAX功能,使Web应用程序能够实现更流畅、响应更快的用户体验。这个实例源码是作者在学习AJAX和使用AjaxAnywhere框架时创建的,适合初学者或者希望...

    ajaxAnywhere局部刷新(一)

    AjaxAnywhere是一个基于JavaScript和Java的库,它通过在服务器端生成Ajax所需的JavaScript代码,简化了Ajax应用的开发。这个库特别适合那些已经存在大量JSP或Servlet的项目,无需大规模重构就能添加Ajax功能。...

    ajaxanywhere用法.rar

    **AjaxAnywhere:深入理解与应用** AjaxAnywhere是一个强大的JavaScript库,专为提升Web应用程序的用户体验而设计,尤其在实现异步...不过,记得在实际开发中,要根据项目需求和目标用户群体选择最合适的工具和技术。

    ajaxanywhere 例子 绝对可用

    3. **易于集成**:由于其设计目标是简化开发过程,AjaxAnywhere提供了一套简单的API,使得开发者能够快速地将Ajax功能添加到现有的Web应用中。 4. **与服务器端框架兼容**:AjaxAnywhere不仅适用于纯JavaScript环境...

    ajaxAnywhere 例子

    5. **AjaxAnywhere API**:学习AjaxAnywhere提供的各种方法,如`AjaxAnywhere.request()`用于发起请求,`AjaxAnywhere.updateElement()`用于更新页面元素等。 6. **数据格式化**:了解如何处理JSON数据,包括序列化...

    ajaxAnyWhere局部刷新框架

    2. **易用性**:其API简洁明了,开发人员可以快速上手,减少学习成本。 3. **兼容性**:该框架支持多种浏览器,包括IE、Firefox、Chrome、Safari等,满足跨平台需求。 4. **灵活性**:AjaxAnyWhere提供了丰富的配置...

    ajaxAnywhere配置

    ### AjaxAnywhere配置详解 #### 一、AjaxAnywhere简介与特性 **AjaxAnywhere**是一款非常实用的工具,旨在简化Web应用程序中的AJAX...此外,通过不断实践与学习,可以有效提升开发效率,同时也能提高项目的整体质量。

    wincvs、ajaxanywhere+struts示例+easyjweb指南

    通过学习这些资料,开发者不仅可以掌握Wincvs的版本控制技巧,还能了解到如何在Struts框架下利用AjaxAnywhere增强Web应用的交互性,并且能够运用EasyJWeb快速开发Java Web项目。这些都是现代Web开发中的重要技能,...

    搜集的一些资料例如ajaxanywhere、jquery、ssh等

    在这个压缩包文件中,包含了一些关于Web开发的重要技术,如AjaxAnywhere、jQuery和SSH。接下来,我将详细介绍这些技术及其在实际应用中的作用。 首先,AjaxAnywhere是一个用于Java企业级应用的Ajax库,它允许开发者...

    ajaxAnywhere_demo

    10. **库和框架的支持**:现代Web开发中,很多库和框架如jQuery、Vue.js、React.js和Angular.js都提供了更高级别的抽象,简化了Ajax的使用。例如,jQuery的`$.ajax()`和`$.getJSON()`方法,Vue.js的`axios`插件等。 ...

    javascrip经典学习质料,仅作参考

    此外,对于"AjaxanyWhere"这样的示例,你可能会学习到如何创建一个跨页面通信的机制,例如在论坛系统中,用户可以无需刷新页面就能查看新帖子、回复或者进行其他交互。这涉及到JSON格式的数据交换,因为XML在现代...

    sturt2+spring+jdbctemplate做的简易登录留言板,有用户,部门等管理

    这个项目可能是一个学习示例或者基础的Web应用模板,用于演示如何将这些技术有效地集成在一起。下面我们将深入探讨这些关键技术和它们在项目中的作用。 **Struts2** 是一个开源的Java MVC框架,用于构建Web应用程序...

    jquery 动态表格

    文件名"Ajax开发精要——概念、案例与框架AjaxAnywhere选摘"表明这个压缩包可能包含了一些关于Ajax的深入学习材料,包括基本概念、实战案例和可能的框架介绍。对于理解如何在jQuery动态表格中运用Ajax,这些资料将...

Global site tag (gtag.js) - Google Analytics