Ajax 学习之获取服务器的值

<%@ 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">
//创建XMLHttpRequest对象
var xmlhttp;
function createXmlHttp(){
//alert("come in");
//xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); //在IE中不可以
xmlhttp=new XMLHttpRequest();     //都可以创建XMLHttpRequest
return xmlhttp;
}

//处理函数
function deal(){
//请求状态等于4,响应状态=200;
if(xmlhttp.readyState==4){
if(xmlhttp.status==200){          //返回200,表示和服务器正常交互完成
alert(xmlhttp.responseText);//获取服务器返回的结果;
}else{
alert(xmlhttp.status);
}
}
}
//xmlhttp=createXmlHttp();
//alert(xmlhttp);
function send(){
//创建xmlhttpRequest对象
xmlhttp=createXmlHttp();
//绑定状态函数
xmlhttp.onreadystatechange=deal;
alert("come on");
var url="http://localhost:8080/fujindehuodong/ajaxServer.jsp?age=16";      //URL地址是服务器地址,而且必须是绝对地址

xmlhttp.open('get',url,true);
//发送请求;

xmlhttp.send(null);        

}
</script>
</head>
<body>
<div id="msg"></div>
<br/>
<input type="button" value="发 送" onclick="send()"></input>
</body>
</html>

服务器那边的代码:用JSP

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%
int age=Integer.parseInt(request.getParameter("age"));
//system.out.println("age="+age);
String str="";
if(age<18){
str="你是未成年人,不允许访问我们网站";
}else{
str="您已经成年,瞎搞把开始";
}
out.write(str);

%>

原文地址:https://www.cnblogs.com/hqutcy/p/5723775.html