Ajax验证数据唯一性

js:

function checkLoginName() {
var loginName = document.myform.loginName.value;
if (loginName == "" || loginName == null) {
alert('用户名不能为空!');
return false;
} else {
var url = "action.do?method=checkLoginName&loginName=" + loginName;
send(url);
// document.myform.action = "action.do?method=checkLoginName";
// document.myform.submit();
}
}
var xmlHttp;
function createXmlHttp() {

if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("MIcrosoft.XMLHttp");
}
}

function send(url) {
createXmlHttp();
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = processRequest;
xmlHttp.send(null);
}

function processRequest() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
var myfont = document.getElementById("name");
while (myfont.hasChildNodes()) {
myfont.removeChild(myfont.firstChild);
}
var text = document.createTextNode();
text.nodeValue = xmlHttp.responseText;
myfont.appendChild(text);
}
}

}


action:

public ActionForward checkLoginName(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {

LoginDao dao=new LoginDao();

String loginName=request.getParameter("loginName");
loginName=new String(loginName.getBytes("ISO-8859-1"),"UTF-8");
System.out.println(loginName);
int num=dao.check(loginName);
if(num==0){
response.getWriter().println("可用");
response.getWriter().flush();
}else{
response.getWriter().println("已经使用");
response.getWriter().flush();
}
return null;
}

dao:

public int check(String loginName){
Session ss=HibernateSessionFactory.getSession();
ss.beginTransaction();
Query q=ss.createQuery("select loginName from Login where loginName='"+loginName+"'");
List list=q.list();
ss.getTransaction().commit();
ss.close();
return list.size();
}

html:
     <tr>
<td width="100" align="right">
用户名:
</td>
<td align="left">
<input type="text" name="loginName" />&nbsp&nbsp<input type="button" value="检查用户名" onclick="checkLoginName()">
<font color="red" size="2px" id="name"></font></td>
</tr>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值