Jquery的ajax一共有三种请求方式
- $.ajax()
语法:$.ajax({键值对});
注意:
响应编码可以在java代码中编写也可以直接在ajax请求里面写
代码实例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="/js/jquery-3.3.1.min.js"></script>
<script>
//使用ajax方式一请求$.ajax
$(function(){
$("#btn").click(function(){
$.ajax({
//1.请求路径
url:"ajaxServlet",
//3.携带数据
//只有一对数据的化,不要带{}
data:"user=dawn",
//4.请求方式
type:"post",
//5.请求成功,回调函数
success:function(data){
alert(data);
},
//6.请求失败时,显示内容
error:function(){
alert("出错了");
},
//响应格式
dataType:"text"
})
})
})
</script>
</head>
<body>
<button id="btn">ajax请求</button>
</body>
</html>
- $.get()
语法:$.get(url, [data], [callback], [type])
参数:
url:请求路径
data:请求参数
callback:回调函数
type:响应结果的类型
代码实例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="/js/jquery-3.3.1.min.js"></script>
<script>
//使用ajax方式二请求$.get
$(function(){
$("#btn").click(function(){
$.get("ajaxServlet",{user:"dawn"},function(data){
alert(data);
},"text");
})
})
</script>
</head>
<body>
<button id="btn">ajax请求</button>
</body>
</html>
- $.post()
语法:$.post(url,[data],[callback],[type])
参数:
url:请求路径
data:携带数据
callback:回调函数
type:响应类型
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="/js/jquery-3.3.1.min.js"></script>
<script>
//使用ajax方式三请求$.post
$(function(){
$("#btn").click(function(){
$.post("ajaxServlet",{user:"dawn"},function(data){
alert(data);
},"text");
})
})
</script>
</head>
<body>
<button id="btn">ajax请求</button>
</body>
</html>
servlet代码
package com.dawm.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/ajaxServlet")
public class AjaxServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
String user = request.getParameter("user");
System.out.println(user);
response.getWriter().write("收到了");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}