下面先看看最简单的通过超链接提交ajax请求:
首先,初始化4个ActionLink,测试4种各有区别的ajax请求
第一种,通过组件的addBehavior方法,添加一个DefaultAjaxBehavior,并重写其onAction方法,以此来重新定义其响应结果。
private ActionLink greetLink = new ActionLink("toGreet", "greet");addControl(greetLink);greetLink.addBehavior(new DefaultAjaxBehavior(){@Overridepublic 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(){@Overridepublic ActionResult onAction(Control source) {ajaxTable.onProcess();return new ActionResult(ajaxTable.toString(),ActionResult.HTML);}});@Overridepublic 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 requestsortTable(event);// Prevent the default browser behavior of navigating to the linkreturn 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 tablejQuery("#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(){@Overridepublic ActionResult onAction(Control source) {return new ActionResult(ajaxForm.toString(),ActionResult.HTML);}});cancel.addBehavior(new DefaultAjaxBehavior(){@Overridepublic 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 loadedjQuery(document).ready(function() {// Register a 'click' handler on the submit buttonjQuery("#ajaxForm_subAjaxForm, #ajaxForm_cancelAjaxForm").live('click', function(event){// Post form to serverpostForm(event);// Prevent the default browser behavior of navigating to the linkreturn false;})})function postForm(event) {// Retrieve the Form and submit button elementsvar form = jQuery("#ajaxForm");var submit = jQuery(event.currentTarget);// The server URL can be retrieved from the Form 'action' eventvar 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 responseform.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 itvar dateSetupScript = jQuery('#ajaxForm_date-js-setup').html();eval(dateSetupScript);// Provide user feedbackvar feedbackDiv = jQuery('#form-msg');// Check for form errorsif(jQuery('#ajaxForm-errors').length == 0) {feedbackDiv.removeClass('errorMsg').addClass('infoMsg');// Set feedback message depending on which button was clickedif (submit.attr('name') == 'subAjaxForm') {feedbackDiv.html("表单提交成功");} else {feedbackDiv.html("取消表单");}} else {feedbackDiv.removeClass('infoMsg').addClass('errorMsg');feedbackDiv.html("表单包含错误");}});}