jsp用ajax完成局部刷新代码

//作为一个初学者在网上找了几天没有解决自己动手写一个ajax的小程序,于是自己总结下来,

//可以把代码完全复制到一个eclipse工程里,观看效果!

1、在java-web工程WebContent下新建一个test1文件夹,建立1.jsp文件

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
var xmlhttp=CreateHttpRQ();
//创建ajax对象
function CreateHttpRQ(){

if(window.navigator.appName=="Microsoft Internet Explorer"){
try{
return new ActiveXObject("Microsoft.XMLHTTP");


}catch(E){
return null;
}
}else{
return new XMLHttpRequest();
}
}
//这是用来检测创建对象是否成功的,如果对象都没创建成功,就不要谈往下做了
 if(xmlhttp!=null){
window.status="chenggong";

//这是检测与服务器传输状态的函数,
function OnStatusChange(){
if(xmlhttp.readyState==4){
if(xmlhttp.status==200){
document.getElementById("message").innerHTML=xmlhttp.responseText;
}else{
document.getElementById("message").innerHTML=xmlhttp.status;
}
}
}
//失去焦点时,执行的函数
function OnBlur(obj) {
var n=obj.value;
//这个地址是绝对地址,不能用相对地址
url="http://localhost:8080/testanything/test1/2.jsp?name="+n;
xmlhttp.open("GET",url,true);
xmlhttp.onreadystatechange=OnStatusChange;
xmlhttp.send(null);
}


</script>
</head>
<body>
<form action="">
用户名:<input type="text" name="username" onblur="OnBlur(this)" />:<div id="message"></div><br/>
密码:<input type="password" name="password" />
<input type="submit" value="提交"/>


</form>
</body>
</html>

2、在新建一个2.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String na=request.getParameter("name");
if(na!=null||!na.equals("")){
if(na.equals("hello")){
out.print("用户存在");
}else{
out.print("用户不存在,可以注册");
}
}

%>


</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_33500630/article/details/55258840