这里DAO层代码就不写了,DAO使用布尔来判断,先从的jQuery的来讲,先获取需要验证的ID值。
$("#APKName").bind("blur",function(){
//ajax后台验证--APKName是否已存在
$.ajax({
type:"GET",//请求类型
url:"apkexist.do",//请求的url
data:{APKName:$("#APKName").val()},//请求参数
dataType:"json",//ajax接口(请求url)返回的数据类型
success:function(data){//data:返回数据(json对象)
if(data.APKName == "empty"){//参数APKName为空,错误提示
alert("APKName为不能为空!");
}else if(data.APKName == "exist"){//账号不可用,错误提示
alert("该APKName已存在,不能使用!");
}else if(data.APKName == "noexist"){//账号可用,正确提示
alert("该APKName可以使用!");
}
},
error:function(data){//当访问时候,404,500 等非200的错误状态码
alert("请求错误!");
}
});
成功回调函数成功的话,就判断数据的值,如果空的英文,就是为空。这里的空是控制层返回来的值。
/**
* 验证APK名/称唯一性
*/
@RequestMapping("apkexist")
@ResponseBody
public Object apkexist(String APKName) {
HashMap<String, String> resultMap = new HashMap<String, String>();
if (StringUtils.isNullOrEmpty(APKName)) {
resultMap.put("APKName", "empty");
} else {
AppInfo appInfo = null;
try {
appInfo = appinfoService.getAppInfo(null, APKName);
} catch (Exception e) {
e.printStackTrace();
}
if (null != appInfo)
resultMap.put("APKName", "exist");
else
resultMap.put("APKName", "noexist");
}
return JSONArray.toJSONString(resultMap);
}
这里要注意的是必须要加上注解@ResponseBody,不然会报错的,还有一个重要的必须在用用SpringMVC的配置文件中加入配置使用FASTJSON进行JSON转换。
<mvc:message-converters>
<!-- 配置字符编码为UTF-8,解决乱码 -->
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- 配置使用fastjson进行json转换 -->
<bean
class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>application/json</value>
</list>
</property>
<property name="features">
<list>
<!-- Date的日期转换器 -->
<value>WriteDateUseDateFormat</value>
</list>
</property>
</bean>
</mvc:message-converters>