actionBean+ajax了解ajax的使用原理。
值得一提的是actionBean在页面中使用ajax,actionBean必须把返回值保存在输出流PrintWrite中,当然也可以无返回值;并且不能
跳转,也就是返回null.看下面的actionBean的代码.
String uname = request.getParameter("uname");
boolean isExists = this.userbiz.isExists(uname);
PrintWriter out = response.getWriter();
out.print(isExists); //业务返回结果保存在输出流
return null; //返回null
页面要创建XmlHttpRequest核心对象,并且设置回调函数,具体JS代码如下
//创建XmlHttpRequest核心对象方法
function createXmlHttpRequest(){
if(window.XMLHttpRequest)
return new XMLHttpRequest; //非IE浏览器
else if(window.ActiveXObject){
try{
return new ActiveXObject("Msxml2.XMLHTTP");}
catch(e){
try{return new ActiveXObject("Microsoft.XMLHTTP");}
catch(e){}
}
}
}
var xmlHttpRequest;//全局xmlHttpRequest变量
//调用检验方法
function checkuname(oCtrl){
var uname=oCtrl.value;
if(!uname){
alert("用户名不能为空");
oCtrl.focus();
return;
}
var url="user.do?op=doLogin&uname="+uname;
xmlHttpRequest=createXmlHttpRequest();
xmlHttpRequest.onreadystatechange=huidiao; //设置或掉函数
xmlHttpRequest.open("GET",url,true); //初始化xmlHttpRequest组件,true为异步调用,即send发送请求后不用响应继续执行后
面的JS语句
xmlHttpRequest.send(null);//发送请求
}
//回调函数
function huidiao(){
if(xmlHttpRequest.status==200 && xmlHttpRequest.readyState==4){
var b=xmlHttpRequest.responseText; //获取actionBean返回的文本,注意是文本
if(b=="true")
alert("用户名存在");
else
alert("用户名不存在");
}
}
xmlHttpRequest.status 200表示正常,404表示没有找到访问文件,500服务器端错误
xmlHttpRequest.readyState 有5种状态,0未初始化,1已初始化,2发送请求,3开始接收结果,4接受结果完毕