Json方式:
前端代码:
jQuery(function($){
$("#bumen").blur(function(){
//alert("123");
var contant = this.value;
if(contant==null||contant==""){
$("#d_deptName").text("请输入部门名");
$("#d_deptName").css("color","red");
} else{
$.ajax({
url:"${ctx }/sysadmin/deptAction_isExist",
type:"post",
data:{
deptName:$.trim(this.value)
//deptName:this.value
},
dataType: "json",//如果不写dataType,data的数据就是字符串。设置了后底层会parse一下变成原先的格式
success:function(data){
if(data){
/* $("#d_deptName").html("存在"); */
$("#d_deptName").text("部门已存在,无法创建");
$("#d_deptName").css("color","green");
}else{
/* $("#d_deptName").html("不存在"); */
$("#d_deptName").text("部门可以创建");
$("#d_deptName").css("color","red");
}
}
})
}
});
});
后台action代码:
String sql = "from Dept where deptName=?";
Object[] params = {model.getDeptName()};
//int[] arr = {1};
List<Dept> dList = deptService.find(sql,Dept.class,params);
boolean flag =false;
if(dList.size()>0){
flag=true;
this.push(flag);
}else {
flag=false;
this.push(flag);
}
return "dList";
结果集:
<package name="sysadmin" namespace="/sysadmin" extends="json-default">//这里因为整合struts所以必须继承json-defaut包,他里面继承了struts的包
<result name="dList" type="json"></result> //这里注意type必须写json,因为ajax异步自动跳转回请求页面所以这里不需要跳转页面
</action>
</package>
流方式:
如果ajax中参数放在链接中url:"deptAction_deptNameExist.action?deptName="+deptName,那么如果deptName是中文,就会出现乱码错误
解决方案一
//随便type采用get还是post,我们采用页面二次编码,服务端解码的方式,去解决乱码问题
//对中文进行二次编码
前端: deptName = encodeURI(encodeURI(deptName));
ajax。。。。
后台://对客户端的内容进行解码
//String deptName = URLDecoder.decode(model.getDeptName());
//最后写到流中,输出到前台
HttpServletResponse response = ServletActionContext.getResponse();
response.getWriter().write(result);