jsp代码
<input type="text" name="productname" id="productname" value="" οnblur="javascript:myCheck()"/>
js 代码
var xmlHttp = newXMLHttpRequest();
function newXMLHttpRequest() {
var xmlreq;
if (window.XMLHttpRequest) {
xmlreq = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
xmlreq = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e1) {
try {
xmlreq = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e2) {}
}
}
return xmlreq;
}
//检查_入口
function myCheck(){
var name = $("#productname").val();
if(name == "" || name == null ){
alert("名不能为空");
document.forms['giftdetailform'].productname.focus();
}else{
var url='giftDetail.do?method=checkName&productname='+encodeURI(name);
xmlHttp.open("GET", url);
xmlHttp.onreadystatechange = checkName; //回调函数
xmlHttp.send(null);
}
}
//检查_ajax方法
function checkName(){
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
var json = eval("(" + xmlHttp.responseText + ")");
if(json.res == 1){
alert("名已经存在");
document.forms['giftdetailform'].productname.focus();
}
}
}
}
Action 方法
public ActionForward checkName(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception{
response.setContentType("application/json");// 设置返回数据类型为xml格式
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
StringBuffer buf = new StringBuffer();
JSONObject jsonResult = new JSONObject();
String name = request.getParameter("productname");
List<GiftDetailForm> listgdf = giftDetailManager.findByName(name.trim());// 查询方法
if (listgdf.isEmpty()) {
buf.append(0);
}else{
buf.append(1);
}
jsonResult.put("res",buf.toString());
out.print(jsonResult.toString());
out.close();
return null;
}