struts2 ajax 驗證使用者名稱是否存在
<%@ page contenttype="text/html; charset=gb2312" language="java" import="java.sql.*" errorpage="" %>
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=gb2312" />
<title>無標題文檔</title>
</head>
<body>
<tr>
<td class="label">用 戶 名:</td>
<td><s:textfield onblur="checkusername(this,'/register!check.action')" css教程class="inputstyle" name="user.name"/></td>
<td width="150px;"><span id="namemessage"></span><s:fielderror cssclass="filederrorclass" fieldname="name"/></td>
</tr>
</body>
</html>
xml文檔
<package name="ajaxuser" extends="網頁特效on-default">
<action name="register" class="com.test.user.registeraction">
<result name="input">/user/register.網頁特效p/jsp.html target=_blank >jsp教程</result>
<result name="success">/user/register_message.jsp</result>
<result name="myjson" type="json"></result>
</action>
</package>
action.代碼
public string check() throws exception {
actioncontext ctx = actioncontext.getcontext();
https教程ervletrequest request = (httpservletrequest)ctx.get(servletactioncontext.http_request);
string username = request.getparameter("inputname");
if(checkuserexit(username)) {
this.registered = true;
}
return "myjson";
}
js代碼
var xmlhttp;
var currentname;
function createxmlhttprequest() {
if (window.activexobject) {
xmlhttp = new activexobject("microsoft.xmlhttp");
}
else if (window.xmlhttprequest) {
xmlhttp = new xmlhttprequest();
}
}
function checkusername(field,url) {
var name = field.value;
if(name=="" || name.length<3) {
document.getelementbyid("namemessage").innerhtml="使用者名稱應該不小於3位";
return;
}else {
createxmlhttprequest();
url = url+"?inputname="+name;
currentname = name;
xmlhttp.open("get", url);
xmlhttp.onreadystatechange = callback;
xmlhttp.send(null);
}
}
function callback() {
if (xmlhttp.readystate == 4) {
if (xmlhttp.status == 200) {
var user = eval('(' + xmlhttp.responsetext + ')');
if(user.registered) {
document.getelementbyid("namemessage").innerhtml ="<font color='red'>"+currentname+", 已經被註冊 !</font>";
}else {
document.getelementbyid("namemessage").innerhtml = "<font color='green'>"+currentname+", 可以註冊 !</font>";
}
}
}
}