ajax 实例

jsp页面代码:

<script type="text/javascript">

var xmlHttp;

function createXMLHttp(){
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}else{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}

function checkUsername(){
var username=document.getElementById("user_name").value;
var url="UserAction.action?method=checkUsername&user_name="+username;
createXMLHttp();
xmlHttp.onreadystatechange=checkUsernameCallback;
xmlHttp.open("post",url,true);
xmlHttp.send();
document.getElementById("info").innerHTML="正在验证······";
}

function checkUsernameCallback(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
var flag=xmlHttp.responseText;
if(flag==1){
document.getElementById("info").innerHTML="输入正确!";
document.getElementById("info").style.color="green";
}else{
document.getElementById("info").innerHTML="输入有误!";
document.getElementById("info").style.color="red";
document.getElementById("user_name").focus();
}
}else{
document.getElementById("info").innerHTML="输入有误!";
document.getElementById("info").style.color="red";
document.getElementById("user_name").focus();
}
}
}

</script>

 

 

 

后台action代码:

try {
/** 获取response对象 */
HttpServletResponse response = ServletActionContext.getResponse();
/** 获取输出out对象 */
PrintWriter out = response.getWriter();
if(!user.equals(null)){
out.print(1);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

你可能感兴趣的:(Ajax)