使用JQuery进行普通ajax异步请求后台的参考小例子
//验证年度是否在数据库中已经存在
//页面部分JS y为年度的值 spanId 为页面提示信息的Id
//ajax验证年度是否已经存在
function ajax_request(y,spanId){
$.ajax({
type: "POST",
url: "<%=webapp%>/admin/admin_checkYYYYRepeat.action",
data: "yyyy="+y,
async:false,//同步请求
success: function(msg){
//alert("---- AJAX返回消息:" + msg);
if(msg == "0"){
addWarnInfo(spanId,'*');
document.getElementById("yyyyIsExist").value = false;
}else{
addWarnInfo(spanId,'*该年度已经存在,不能再新增!');
document.getElementById("yyyyIsExist").value = true;
}
},
error: function(msg){
alert("发送失败,请重新发送!");
return false;
}
});
}
后台部分代码
//action部分
/**
* 功能:校验年度是否已经存在 *
* @author lixinyao
* @version 1.0
* @param yyyy
* @return 0 表示不存在 1 表示已经存在
*/
public void checkYYYYRepeat() {// Action方法切忌有参数否则无法调用
int count = adminService.yyyyIsExist(yyyy);
System.out.println("count:"+count);
HttpServletResponse response =response();
PrintWriter out = null;
try {
out = response.getWriter();
// writer参数最好转成String,否则在页面上可能出现异常情况
out.write(count+"");
} catch (IOException e) {
e.printStackTrace();
} finally {
out.flush();
out.close();
}
}
//注意 要获得由前端JS传来的值 action 必须 声明变量 yyyy 并提供set get方法
//实现类部分
/**
* 判断年度是否已经存在
* @return
*/
public int yyyyIsExist(String yyyy){
StringBuffer sb = new StringBuffer();
sb.append(" select count(t.id) from t_object_job t where t.yyyy=? ");
List list = null;
List params = new ArrayList();
params.add(yyyy);
try{
list = hibernateDao.queryBySqlWithParams(sb.toString(), params.toArray());
}catch(Exception e){e.printStackTrace();}
if(list != null){
return Integer.valueOf(list.get(0).toString());
}else{
return 0;
}
}