1按钮 2010-11-7 author:heguikun
<input type="text" name="petInfo.petName" value="晴天大圣" οnblur="return checkPetExists(this)">
2.脚本
<script type="text/javascript">
//宠物名验证并使用Ajax技术
var xmlHttpRequest;//必须要设置全局变量,否则报对象未定义
function createXmlHttpRequest()
{
if(window.ActiveXObject)
{//IE浏览器
xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP");
}
else{//非IE浏览器
xmlHttpRequest=new XMLHttpRequest();
}
return xmlHttpRequest;
}
function checkPetExists(oCtl)
{
var petName=oCtl.value;
if(!petName)
{
alert("宠物名不能为空!");
oCtl.focus();
return;
}
//请求字符串
var url="pet.do?operate=doCheckUserExists&petName="+petName;
//1.创建XMLHttpRequest组建
var xmlHttpRequest=createXmlHttpRequest();
//2.设置回调函数
xmlHttpRequest.onreadystatechange=petaAjax;
//3.初始化xmlHttpRequest组件
xmlHttpRequest.open("GET",url,true);
//发送请求
xmlHttpRequest.send(null);
}
function petaAjax()
{
if(xmlHttpRequest.readyState==4&&xmlHttpRequest.status==200)
{
var b=xmlHttpRequest.responseText;//获取打印的只
if(b=="true")
{
alert("该宠物名已被使用");
}else
{
alert("该宠物名可用!");
}
}
}
</script>
3.Action
//ajax技术
public ActionForward doCheckUserExists(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws IOException {
String petName = request.getParameter("petName");
petName= new String(petName.getBytes("iso-8859-1"), "gbk");//iso-8859-1
System.out.println(petName);
List list=allBiz.query("from PetInfo where petName='"+petName+"'");
PrintWriter out=response.getWriter();
if (list!=null&&list.size()>0) {
out.write("true");//打印出来时为了回调函数获取这个字符串
}else
{
out.write("false");
}
return null;
}