前端代碼:文章來源:http://www.zghlxwxcb.cn/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>
后端代碼:文章來源地址http://www.zghlxwxcb.cn/news/detail-527664.html
@WebServlet("/studentInfo")
public class StudentInfoServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//假設(shè)客戶端發(fā)來的請求形如 /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);
}
}
到了這里,關(guān)于ajax構(gòu)造get、post、put請求的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!