[Apache Click快速开发]为组件添加Ajax行为

Apache中有个名为Behavior的接口,用来定义组件的行为。查看源码后发现Click只提供了一种行为的实现,即:DefaultAjaxBehavior

通过查看Click源代码不难发现其AbstractControl中定义了一个addBehavior方法,为组件添加一个行为。因此,所有组件都具有了添加行为的方法,因为所有组件均继承自AbstractControl这个抽象类。

[下面是Click各组件继承顺序]

下面先看看最简单的通过超链接提交ajax请求:

首先,初始化4个ActionLink,测试4种各有区别的ajax请求

第一种,通过组件的addBehavior方法,添加一个DefaultAjaxBehavior,并重写其onAction方法,以此来重新定义其响应结果。

private ActionLink greetLink = new ActionLink("toGreet", "greet"); addControl(greetLink); greetLink.addBehavior(new DefaultAjaxBehavior(){ @Override public ActionResult onAction(Control source) { return new ActionResult("Hi, I am Apache Click,came from Carlifornia"); } });$("#greet-link").click(function(){ $.post($(this).attr("href"),$(this).attr("id")+"=2",function(data){ $("#msg").html(data); }); return false; });

第二种,htm中通过指定请求参数pageAction为Page中的调用方法名,本例中为sayHello

$("#hello-link").click(function(){ $.post($(this).attr("href"),"pageAction=sayHello",function(data){ $("#msg").html(data); }); return false; });private ActionLink helloLink = new ActionLink("sayHello","hello"); addControl(helloLink); public ActionResult sayHello(){ return new ActionResult("Hello, Welcome!"); }

第三种,传递参数,并返回json格式数据

private ActionLink jsonLink = new ActionLink("jsonLink","json"); addControl(jsonLink); public ActionResult jsonRequest(){ String type = getContext().getRequestParameter("type"); String currentDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); String json = "{\"date\":\""+currentDate +"\",\"msg\":\"Json Result Returned,request parameter \'type:"+type+"\'\"}"; return new ActionResult(json); }$("#json-link").click(function(){ $.post($(this).attr("href"),"pageAction=jsonRequest&type=ajax",function(data){ var result = $.parseJSON(data); $("#msg").html("["+result.date+"]"+result.msg); }); return false; });

第四种,返回xml格式数据

private ActionLink xmlLink = new ActionLink("xmlLink","xml"); xmlLink.setId("xml-link"); addControl(xmlLink); public ActionResult xmlRequest(){ String xml = "<result><msg>Hello Xml Result From Ajax Request. </msg></result>"; return new ActionResult(xml); }$("#xml-link").click(function(){ $.post($(this).attr("href"),"pageAction=xmlRequest",function(data){ var result = $(data); $("#msg").html(result.find("result").text()); }); return false; });


接下来,看看怎么来为table做一个ajax无刷新的分页

下面会省掉初始化table中column的过程

private Table ajaxTable = new Table("ajaxTable");private Form ajaxForm = new Form("ajaxForm");

关键的几个地方为:为table,form添加defaultAjaxBehavior、在getElements方法中添加处理的js脚步导入

ajaxTable.getControlLink().addBehavior(new DefaultAjaxBehavior(){ @Override public ActionResult onAction(Control source) { ajaxTable.onProcess(); return new ActionResult(ajaxTable.toString(),ActionResult.HTML); } });@Override public List<Element> getHeadElements() { if (headElements == null) { headElements = super.getHeadElements(); headElements.add(new JsImport("/js/jqueryui/jquery-1.6.2.js")); //headElements.add(new JsImport("/js/form-ajax.js")); headElements.add(new JsImport("/js/table-ajax.js")); } return headElements; }

table-ajax.js:

jQuery(document).ready(function() { jQuery("#ajaxTable th a,.pagelinks a ,.pagelinks-nobanner a").live('click', function(event){ // Make ajax request sortTable(event); // Prevent the default browser behavior of navigating to the link return false; }) }) function sortTable(event) { var link = jQuery(event.currentTarget); var url = link.attr('href'); jQuery.get(url, function(data) { // Update the table container with the new table jQuery("#tableContainer").html(data); }); }

最后,来做一个ajax提交表单

private Form ajaxForm = new Form("ajaxForm");

初始化表单,包括添加元素,为提交和取消按钮添加ajax行为

TextField account = new TextField("account","账号", true); account.setTitle("不少于6位"); account.setMinLength(6); ajaxForm.add(account); ajaxForm.add(new DateField("birth", "出生日期")); ajaxForm.add(new PasswordField("passwd1", "密码", true)); ajaxForm.add(new PasswordField("passwd2", "确认密码", true)); Submit sub = new Submit("subAjaxForm","提交"); ajaxForm.add(sub); Submit cancel = new Submit("cancelForm", "取消"); ajaxForm.add(cancel); sub.addBehavior(new DefaultAjaxBehavior(){ @Override public ActionResult onAction(Control source) { return new ActionResult(ajaxForm.toString(),ActionResult.HTML); } }); cancel.addBehavior(new DefaultAjaxBehavior(){ @Override public ActionResult onAction(Control source) { ajaxForm.clearErrors(); ajaxForm.clearValues(); return new ActionResult(ajaxForm.toString(),ActionResult.HTML); } }); ControlRegistry.registerAjaxTarget(ajaxForm);//这行代码很重要,将form指定为ajax请求的目标

之后,还要在getElements方法中导入js脚本(这不是必须,你也可以在Htm中直接书写js脚本)

headElements.add(new JsImport("/js/form-ajax.js"));

脚本我是在apache官方上面copy而来,稍加修改

jQuery.noConflict(); // Register a function that is invoked as soon as the DOM is loaded jQuery(document).ready(function() { // Register a 'click' handler on the submit button jQuery("#ajaxForm_subAjaxForm, #ajaxForm_cancelAjaxForm").live('click', function(event){ // Post form to server postForm(event); // Prevent the default browser behavior of navigating to the link return false; }) }) function postForm(event) { // Retrieve the Form and submit button elements var form = jQuery("#ajaxForm"); var submit = jQuery(event.currentTarget); // The server URL can be retrieved from the Form 'action' event var url = form.attr('action'); var formData = form.serialize(); formData+='&'+form.attr('id')+'=1'; formData+='&'+submit.attr('name')+'='+submit.attr('value'); jQuery.post(url, formData, function(data) { // Replace the entire Form with the server response form.replaceWith(data); // Replacing the Form with the Form from the Ajax response, means all // event bindings are lost. For example the DateField button won't show // the Calendar. Here we find the DateField setup script, and evaluate it var dateSetupScript = jQuery('#ajaxForm_date-js-setup').html(); eval(dateSetupScript); // Provide user feedback var feedbackDiv = jQuery('#form-msg'); // Check for form errors if(jQuery('#ajaxForm-errors').length == 0) { feedbackDiv.removeClass('errorMsg').addClass('infoMsg'); // Set feedback message depending on which button was clicked if (submit.attr('name') == 'subAjaxForm') { feedbackDiv.html("表单提交成功"); } else { feedbackDiv.html("取消表单"); } } else { feedbackDiv.removeClass('infoMsg').addClass('errorMsg'); feedbackDiv.html("表单包含错误"); } }); }


Click中Ajax特性就介绍到这里,下午太容易犯困了,休息休息~











  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值