前端代码:文章来源:https://www.toymoban.com/news/detail-527664.html
<body>
<div class="one">
</div>
<button id="doGet">get</button>
<button id="doPost">post</button>
<button id="doPut">put</button>
<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
<script>
let doGetBtn = document.querySelector('#doGet');
doGetBtn.onclick = function(){
$ajax({
type:'get',
url:'hello',
success:function(body) {
let div = document.querySelector('.one');
div.innerHTML = body;
}
});
}
let doPostBtn = document.querySelector('#doPost');
doGetBtn.onclick = function(){
$.ajax({
type:'post',
url:'hello',
success:function(body) {
// console.log(body);
let div = document.querySelector('.one');
div.innerHTML = body;
}
});
}
let doPutBtn = document.querySelector('#doPut');
doGetBtn.onclick = function(){
$.ajax({
type:'put',
url:'hello',
success:function(body) {
// console.log(body);
let div = document.querySelector('.one');
div.innerHTML = body;
}
});
}
</script>
</body>
</html>
后端代码:文章来源地址https://www.toymoban.com/news/detail-527664.html
@WebServlet("/studentInfo")
public class StudentInfoServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//假设客户端发来的请求形如 /studentInfo?classId=104&studentId=3
//就可以通过getParameter 方法来拿到这两个 id 的值
resp.setContentType("text/html;charset=utf8" );
String classId = req.getParameter("classId");
String studentId = req.getParameter("studentId");
resp.getWriter().write("classId"+classId+","+"studentId"+ studentId);
}
}
@WebServlet("/StudentInfo2")
public class StudentInfoServlet2 extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("test/html;charset=utf8");
String studentId = req.getParameter("studentId");
String classId = req.getParameter("classId");
resp.getWriter().write("classId"+classId+","+"studentId"+ studentId);
}
}
到了这里,关于ajax构造get、post、put请求的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!