基于Struts2框架下实现Ajax有两种方式,第一种是原声的方式,另外一种是struts2自带的一个插件。

js部分调用方式是一样的:

JS代码:

 function testAjax() {

     var $userNameInput = $("#ajax_username");
var userName = $userNameInput.val(); $.ajax({
url : "originAjax.action",
type : "GET",
data : "ajaxField=" + userName,
success : function(data, textStatus) {
alert(data);
}
});
}

第一种原生的实现方式:

Action中创建一个方法:

    private String username;

    public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public void checkUserName() throws IOException { HttpServletResponse response = ServletActionContext.getResponse();
PrintWriter writer = response.getWriter();
writer.print("hello " + username);
writer.flush();
writer.close();
}

struts.xml中配置:

<action name="originAjax" class="TestAction" method="checkUserName" />  

这种方式不太推荐使用。

这里重点讲解下第二种方式:

1.引入struts2-json-plugin-2.5.2.jar

2.Action中添加类似的如下代码:

private String result;
public String getResult() {
return result;
} public void setResult(String result) {
this.result = result;
}
/**
*
* AJAX for check MerchantAccount start
*
* */
private String merchantAccount; public String getMerchantAccount() {
return merchantAccount;
} public void setMerchantAccount(String merchantAccount) {
this.merchantAccount = merchantAccount;
} // AJAX for check Merchant
public String checkMerchantAccountMethod() throws IOException { AppResultJsonBean ajaxResultJsonBean = new AppResultJsonBean(); if (StarCloudStringUtils.isEmpty(merchantAccount)) { ajaxResultJsonBean.setIsOK(false);
ajaxResultJsonBean.setData(null);
ajaxResultJsonBean.setResultCode(-1);
ajaxResultJsonBean.setResultMessage("商家账号不能为空");
ajaxResultJsonBean.setOther(null); JSONObject ajaxResultJsonData = JSONObject
.fromObject(ajaxResultJsonBean); this.result = ajaxResultJsonData.toString(); return SUCCESS;
} if (!StarCloudStringUtils.isMobile(merchantAccount)) { ajaxResultJsonBean.setIsOK(false);
ajaxResultJsonBean.setData(null);
ajaxResultJsonBean.setResultCode(-2);
ajaxResultJsonBean.setResultMessage("商家账号格式不合法");
ajaxResultJsonBean.setOther(null); JSONObject ajaxResultJsonData = JSONObject.fromObject(ajaxResultJsonBean); this.result = ajaxResultJsonData.toString(); return SUCCESS;
} 。。。
MerchantBean checkMerchantBean = merchantIService.findMerchantByAccount(merchantAccount); if (checkMerchantBean != null) { ajaxResultJsonBean.setIsOK(true);
ajaxResultJsonBean.setData(null);
ajaxResultJsonBean.setResultCode(0);
ajaxResultJsonBean.setResultMessage("商家账号可用");
ajaxResultJsonBean.setOther(null); JSONObject ajaxResultJsonData = JSONObject.fromObject(ajaxResultJsonBean); this.result = ajaxResultJsonData.toString(); return SUCCESS;
} else {
ajaxResultJsonBean.setIsOK(false);
ajaxResultJsonBean.setData(null);
ajaxResultJsonBean.setResultCode(-3);
ajaxResultJsonBean.setResultMessage("商家账号不存在");
ajaxResultJsonBean.setOther(null); JSONObject ajaxResultJsonData = JSONObject.fromObject(ajaxResultJsonBean); this.result = ajaxResultJsonData.toString();
return SUCCESS;
}
}
/**
*
* AJAX for check MerchantAccount start end
*
* */

Struts.xml中配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts> <!-- AJAX
1.引入Jar包
2.所在包必须要继承自JSON-default
3.resultType是JSON
4.附加了一个参数excludeNullProperties,目的是不序列化Action里为null的字段。
5.<result>元素没有name属性,也没有跳转值
-->
<package name="struts_web_product_ajax" extends="json-default">
<!-- 新增商品信息检查账号 -->
<action name="checkMerchantAccountAction" class="controllers.actions.web.product.PrepareAddProductAction" method="checkMerchantAccountMethod">
<result type="json">
<param name="excludeNullProperties">true</param>
<param name="root">result</param>
</result>
</action>
</package>
</struts>

JS中接受返回结果:

返回JSON格式:

JS解析如下:

function checkMerchantAccountAjax() {

    var $merchantAccount = $("#merchantAccount");
var merchantAccount = $merchantAccount.val(); $.ajax({
url : "checkMerchantAccountAction",
type : "GET",
data : "merchantAccount=" + merchantAccount,
success : function(data, textStatus) {
var resultJSONData = JSON.parse(data);//注意这里必须有,因为之前返回的是result="json字符串",但并类型不是JSON
if(resultJSONData.isOK){
$merchantAccount.css("color", "black");
return true;
}else{
$merchantAccount.css("color", "red");
layer.tips(resultJSONData.resultMessage,$merchantAccount, {
tips : [3, '#3595CC'],
time : 4000
});//end tips
return false;
}//end else }//end success
});//end ajax
}// end js

Struts2实现ajax的两种方式的更多相关文章

  1. jquery的ajax和原始的ajax这两种方式的使用方法

    jquery的ajax是对原始的ajax进行的封装,方便用户的使用.下面用代码分别举例各自的使用方式. jquery的ajax发送和接收xml数据格式. $.ajax({ type: "PU ...

  2. Struts2网页面传值两种方式

    第一种方式: /** 列表 */ public String list() throws Exception { List<Role> roleList = roleService.fin ...

  3. ajax的两种方式

    get:var ajax=new XMLHttpRequest();ajax.open('get','__URL__/check_all?val='+check);ajax.send();ajax.o ...

  4. 【TP3.2 + 其他任何PHP框架】编辑、删除、添加数据,返回原分页 (ajax+form两种方式提交均可以)

    1.目的1:在如下的一个页面中,p=2,比如我们删除数据id=13,通过ajax提交{id,p} 这2个参数,就可以了,页面返回json的url参数中原样带上p即可. 2.目的2: 步骤1:在如下页面 ...

  5. 【前台 ajax】web项目前台传递数组给后台 两种方式

    项目使用maven    springMVC 有需求 将前台的数组   在ajax中 送给后台 方式1: 前台代码:[注意:ajax中的属性---traditional:true,  ] 如果Post ...

  6. jquery ajax提交表单数据的两种方式

    http://www.kwstu.com/ArticleView/kwstu_201331316441313 貌似AJAX越来越火了,作为一个WEB程序开发者要是不会这个感觉就要落伍,甚至有可能在求职 ...

  7. ajax的data传参的两种方式

    ajax的data传参的两种方式 本文为转载. 1.[javascript] view plain copy /** * 订单取消 * @return {Boolean} 处理是否成功 */ func ...

  8. SpringMVC实现Action的两种方式以及与Struts2的区别

    4.程序员写的Action可采用哪两种方式? 第一.实现Controller接口第二.继承自AbstractCommandController接口 5.springmvc与struts2的区别? 第一 ...

  9. egg.js 通过 form 和 ajax 两种方式上传文件并自定义目录和文件名

    egg.js 通过 form 和 ajax 两种方式上传文件并自定义目录和文件名 评论:10 · 阅读:8437· 喜欢:0 一.需求 二.CSRF 校验 三.通过 form 表单上传文件 四.通过 ...

随机推荐

  1. 谈谈一些有趣的CSS题目(十二)-- 你该知道的字体 font-family

    开本系列,谈谈一些有趣的 CSS 题目,题目类型天马行空,想到什么说什么,不仅为了拓宽一下解决问题的思路,更涉及一些容易忽视的 CSS 细节. 解题不考虑兼容性,题目天马行空,想到什么说什么,如果解题 ...

  2. UWP开发之Template10实践:本地文件与照相机文件操作的MVVM实例(图文付原代码)

    前面[UWP开发之Mvvmlight实践五:SuspensionManager中断挂起以及复原处理]章节已经提到过Template10,为了认识MvvmLight的区别特做了此实例. 原代码地址:ht ...

  3. Angular2开发笔记

    Problem 使用依赖注入应该注意些什么 服务一般用来做什么 指令一般用来做什么 angular2如何提取公共组件 angular2为什么不需要提公共组件 父组件与子组件之间如何通讯 什么时候应该使 ...

  4. springMVC初探--环境搭建和第一个HelloWorld简单项目

    注:此篇为学习springMVC时,做的笔记整理. MVC框架要做哪些事情? a,将url映射到java类,或者java类的方法上 b,封装用户提交的数据 c,处理请求->调用相关的业务处理—& ...

  5. javascript设计模式:策略模式

    前言 策略模式有效利用组合.委托.多态等技术和思想,可以有效避免多重条件选择语句. 策略模式对开放-封闭原则提供了很好的支持,将算法封装在strategy中,使得他们易于切换.理解.扩展. 策略模式中 ...

  6. RIFF和WAVE音频文件格式

    RIFF file format RIFF全称为资源互换文件格式(Resources Interchange File Format),是Windows下大部分多媒体文件遵循的一种文件结构.RIFF文 ...

  7. ObserverPattern(观察者模式)

    import java.util.ArrayList; import java.util.List; /** * 观察者模式 * @author TMAC-J * 牵一发而动全身来形容观察者模式在合适 ...

  8. 使用github远程仓库

    经过几天对github的研究,终于把自己想完成的给解决了,发现google真的有很多解释,但是很多也会出现一些bug,对于初学者真的很多烦恼,所以整理一份,能给初识github的你有所帮助 一,首先, ...

  9. 太多选择——企业如何选择合适的BI工具?

    在没认清现状前,企业当然不能一言不合就上BI. BI不同于一般的企业管理软件,不能简单归类为类似用于提高管理的ERP和WMS,或用于提高企业效率的OA.BPM.BI的本质应该是通过展现数据,用于加强企 ...

  10. TabLayout + ViewPager

    一.实现思路 1.在build.gradle中添加依赖,例如: compile 'com.android.support:support-v4:23.4.0'compile 'com.android. ...