首先是导入jquery的文件:
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
测试用的ajax请求,后端功能为查询功能:
jsp页面:
$(document).ready(function () {
$("#all").click(function () {
$.ajax({
url: "testServlet",
type: "post",
success: function (data) {
var json= JSON.parse(data);
var content="<table><tr><th>id</th><th>商品名</th><th>备注</th><th>收藏</th></tr>";
$.each(json,function(index,element){
content=content+'<tr><td>'+element.id+'</td><td>'+element.name+'</td><td>'+element.notes+'</td><td><a href="collectServlet?sid='+element.id+'">收藏</ a></td></tr>';
});
content=content+'</table>';
$(".test").html(content);
}
});
});
});
servlet页面:
package com.kevin.servlet;
import java.io.IOException;
import java.util.List;
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 org.json.JSONArray;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.kevin.dao.impl.shopDAOImp;
import com.kevin.pojo.Shop;
/**
* Servlet implementation class testServlet
*/
@WebServlet("/testServlet")
public class testServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public testServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
shopDAOImp shopDAOImp = context.getBean("shopDAO", shopDAOImp.class);
List<Shop> list = shopDAOImp.selectAll();
JSONArray jsonArray = new JSONArray(list);
response.getWriter().print(jsonArray);
}
}
附带的几个jquery小功能:
/* 获取ID为xxx文本框的内容,并进行输出 */
function t001() {
var xxx = $("#xxx").val();
$(".test").html(xxx);
}
/* 隐藏类名为test的div */
function t002() {
$(".test").hide();
}
/* 显示类名为test的div */
function t003() {
$(".test").show();
}