需求:鼠标离开文本框进行数据库查询名称是否重复,存在提示已存在,返回success阻止提交,并显示在文本框后面,不让其提交,不存在则提示可以使用。并返回页面
1. 前端jquery实现
- 写个鼠标输入时进行文本框触发事件(html),
- 文本框加入:autocomplete="off " 属性 ( F5刷新页面时清空文本框 )
<form action="/BuyerFigure.htm" method="post" class="checkFigure">
<input type="text" autocomplete="off" id="buyerName" class="ipt-normal stature" name="buyerName" />
这里是提示信息:<span id="errorbuyerName"></span>
<div class="save-submit">
<input type="submit" onclick="return checkFigure()" value="保存"/>
</div>
</form>
3 . 鼠标离开触发js代码(jquery:需要导入jquery.js)。
$(function() {
//鼠标离文本框判断名称是否重复
//#buyerName 获取要判断的文本框
//绑定propertychange 即刻搜索事件(键盘按下就提示)
$("#buyerName").bind("input propertychange",function(){
$.ajax({
type : "POST",
url : "/checkBuyerFigure.htm",
data : {
//获取文本框的值
buyerName : $("#buyerName").val()
},
dataType : "json",
success : function(data) {
$('#errorbuyerName').empty(); // 清空resText里面的所有内容
$("#errorbuyerName").text(data.msg);
//设置获取submit的,设置submit的属性(false禁止提交,true允许提交)
if(data.msg=="可以使用此名"){
$(".save-summit input").attr("disabled",false);
}
if(data.msg!="可以使用此名"){
$(".save-submit input").attr("disabled",true);
}
}
});
})
}
2. 后端java实现
jquery进入ajax 进入到 Controller 控制器页面,查询是否存在名称并返回信息
/**
* 鼠标离开文本框判断用户是否输入
* @param buyerName 身材名
* @param request
* @return
* @throws Exception
*/
@RequestMapping(value="/checkBuyerFigure",produces="text/html;charset=UTF-8")
@ResponseBody
public String checkBuyerFigure(
String buyerName,
HttpServletRequest request
) throws Exception{
//msg 返回信息
String msg = null;
if(buyerName.equals("") || buyerName==null || buyerName.trim().isEmpty()){
msg = "请填写数据";
}
//数据库查询检验buyerName是否存在 存在返回1,不存在返回0
Integer ret = buyerFigureService.checkBuyerFigure(buyerName);
if(ret == 1 || ret > 1){
msg = "名称已经存在";
}else{
msg = "可以使用此名";
}
JSONObject json = new JSONObject();
json.put("msg", msg);
return json.toString();
}
3. 实现效果