备注:红色代表关键代码
1,第一个ajax,前台页面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
////////下面这个是get方法传递
/*
var url = encodeURL("<%=basePath%>AjavServlet?name=张三");
xmlhttp.open("GET",url,true);
xmlhttp.send();
*/
////////下面这个是post方法传递
xmlhttp.open("POST","<%=basePath%>AjavServlet",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("name=张三");
}
</script>
</head>
<body>
<button type="button" onclick="loadXMLDoc()">请求数据</button>
<div id="myDiv"></div>
</body>
</html>
1,第一个ajax,后台页面
public class AjavServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name");
// name = new String(name.getBytes("ISO-8859-1"),"UTF-8");
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
out.println(new Date());
out.println(name);
out.flush();
out.close();
}
}
2,第二个jquery-ajax,前台页面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script type="text/javascript" src="<%=basePath %>Jquery-1.7.2.min.js"></script>
<script type="text/javascript">
function loadXMLDoc(){
/////// get的第一种写法
/*
$.ajax({
url:"<%=basePath%>AjavServlet",
type:"GET",
data:{name="zhangsansan"},
success:function(data){
document.getElementById("myDiv").innerHTML=data;
}
});
*/
/////// get的第二种写法
$.get("<%=basePath%>AjavServlet",{name="zhangsansan"},function(data){
document.getElementById("myDiv").innerHTML=data;
});
}
</script>
</head>
<body>
<button type="button" onclick="loadXMLDoc()">ÇëÇóÊý¾ÝjqueryAjax</button>
<div id="myDiv"></div>
</body>
</html>
2,第二个jquery-ajax,后台页面与第一个一样