浏览器向服务器发送get请求
浏览器从后台获取数据
JavaScript部分
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
</style>
</head>
<body>
<button id="btn">按钮</button>
</body>
<script src="js/jquery-3.3.1.js"></script>
<script>
$('#btn').click(function(){
$.ajax({
type:'GET',
url:'ajaxTest',
dataType:'json',
success:function(resp){
showResult(resp);
}
});
});
function showResult(result){
for(var stu of result){
console.log(stu.name);
console.log(stu.id);
console.log(stu.sex);
console.log(stu.phone);
}
}
</script>
</html>
Servlet部分
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {LinkedList<Student> students = new LinkedList<Student>();
students.add(new Student(2001,"Tom",true,"18438825932"));
JSONArray result = new JSONArray(students);
response.setCharacterEncoding("UTF-8");
response.setContentType("text/plain");
Writer writer = response.getWriter();
writer.write(result.toString(2));
writer.close();
}
浏览器向服务器发送post请求
浏览器向后台传递数据
JavaScript部分
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
</style>
</head>
<body>
<input type="text" />
<input type="password" />
<button id="btn">按钮</button>
</body>
<script src="js/jquery-3.3.1.js"></script>
<script>
$('#btn').click(function(){
var id = $('input').eq(0).val();
var password = $('input').eq(1).val();
$.ajax({
type:'POST',
url:'postTest',
data:{
method:'login',
id:id,
password:password
},
dataType:'json',
success:function(resp){
console.log("success");
}
});
});
</script>
</html>
Servlet部分
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String id = request.getParameter("id");
String password = request.getParameter("password");
System.out.println(id);
System.out.println(password);
}