js代码
<script type="text/javascript">
var xmlHttp;
var flag = true;
function createXMLHttp(){
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
xmlHttp.overrideMimeType("text/xml");//会出行乱码,加一句这个看看;
}else{
xmlHttp=new ActiveXObject("microsoft.xmlhttp");
}
}
function checkfCODE(){
var fcode= document.getElementById("fCODE").value;
var id=document.getElementById("FID").value;
if(fcode==""){
document.getElementById("message").innerHTML="<font color='red'>区域编号不能为空</font>";
flag = false;
return ;
}
createXMLHttp();
xmlHttp.onreadystatechange = checkfCODECallback;
var url="${pageContext.request.contextPath}/area/area!sameNumCharge.action?formInfo.fCODE="+fcode+"&formInfo.fID="+id;
xmlHttp.open("post",url);
xmlHttp.send(null);
}
function checkfCODECallback(){
if(xmlHttp.readyState==4){
if(xmlHttp.status ==200){
var text = xmlHttp.responseText;
var message=document.getElementById("message");
while(message.hasChildNodes()) {
message.removeChild(message.firstChild);
}
var child = document.createTextNode();
child.nodeValue =text;
message.appendChild(child);
if(text=="已经使用"){
flag= false;
document.getElementById("fCODE").select();//获得焦点,高亮显示。
}else{
flag=true;
}
}
}
}
</script>
Java代码:
/**
*增加区域编号唯一判断
*/
public void sameNumCharge(){
boolean flag=false;
String id = String.valueOf(formInfo.getFID());
AreaInfo info=new AreaInfo();
info.setFCODE(formInfo.getFCODE());
System.out.println(formInfo.getClass().getName());
List<AreaInfo> arrayAreaInfo =manager.findAll(info);
if(id != null && !id.equals("0")){// 表示修改时候的相同编号判断
if(arrayAreaInfo != null && arrayAreaInfo.size()==1){
AreaInfo areainfo = arrayAreaInfo.get(0);
if(formInfo.getFID()==areainfo.getFID()){
flag=true;
}else{
flag=false;
}
}else if(arrayAreaInfo!=null && arrayAreaInfo.size()==0){
flag=true;
}else{
flag=false;
}
}else{ // 表示新增时候的相同编号判断
if(arrayAreaInfo==null || arrayAreaInfo.size()==0){
flag=true;
}else if(arrayAreaInfo!=null && arrayAreaInfo.size()>0){
flag=false;
}
}
PrintWriter out;
try{
HttpServletResponse response=getResponse();
response.setCharacterEncoding("utf-8");
out=response.getWriter();
if(flag){
//可用
out.print("可用");
out.flush();
}else{
//不可用
out.print("已经使用");
out.flush();
}
out.close();
}catch(IOException e){
e.printStackTrace();
}
}
JSP代码:
<s:textfield id="fCODE" name="formInfo.fCODE" οnblur="checkfCODE();"/> <font color="red" size="2px" id="message"></font>
这个用到的地方还真的,只是觉得每次都这么写还是挺麻烦。有简单的方法吗?
参考资料:Ajax :http://i5252592.iteye.com/blog/761770
JS :http://blog.sina.com.cn/s/blog_5f311bdb0100egw4.html