如何用phototype架構實現一個簡單的ajax驗證:
依靠phototype很容易實現
1,首先下載一個phototype.js檔案並將它放在你的工程中,在需要ajax驗證的頁面中匯入該js檔案
2,建立一個簡單的ftl頁面中加入如下代碼
<#include "/error/actionerrors.ftl">
<#assign base=req.contextPath />
<td>*使用者名稱:</td><td><input type="text" name="loginName" id="loginName" size="21" height="21" maxlength="16" onblur="searchSales();"/>
<div id="result"/>
</td>
<script>
function searchSales(){
var loginName = $('loginName').value;
var url = '${base}/regist/checkName.action';
var pars = 'loginName=' + loginName;
var myAjax = new Ajax.Request(
url,
{
method: 'get',
parameters: pars,
onComplete: showResponse
});
}
function showResponse(originalRequest){
//put returned XML in the textarea
var resultDiv=$('result');
resultDiv.innerHTML= originalRequest.responseText;
}
</script>
3,編寫一個action用於處理ajax傳來的請求,請注意我是在webwork2架構下,個人可以根據情況適當的修改,步驟大體都一樣
package action;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.opensymphony.webwork.ServletActionContext;
import com.opensymphony.xwork.ActionContext;
import domain.Admin;
public class CheckNameAction extends BaseAction{
//ServletActionContext.APPLICATION;
//ServletActionContext.SESSION;
//ServletActionContext.PAGE_CONTEXT;
public String execute(){
ActionContext ctx = ActionContext.getContext();
//在webwork中獲得request對象
HttpServletRequest request = (HttpServletRequest)ctx.get(ServletActionContext.HTTP_REQUEST);
//在webwork中獲得response對象
HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);
String loginName=request.getParameter("loginName");
try {
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
List<Admin> list=this.getLoginService().listAdmin();
int count =0;
if(list.size()!=0){
for(Admin admin : list){
if(admin.getUserName().equals(loginName)){
count++;
break;
}
}
}
PrintWriter out = response.getWriter();
if(count==0)
out.println("<font color='green'>恭喜你,使用者名稱可用!</font>");
else
out.println("<font color='red'>很抱歉,使用者名稱不可用!</font>");
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
經過著3大部,然後我們再配置一下action,就可以使用了,很方便。