浅谈ajax在jquery中的请求和servlet中的响应

2020-05-24 21:32:31易采站长站整理

在jsp中,首先,你需要导入jquery的架包:

获取可返回站点的根路径:


<%
String path = request.getContextPath();
%>

在jquery中写ajax请求:


<script type="text/javascript">
$(function(){
$(".B").click(function(){
$.ajax({
type: "GET",
//对应servlet中的方法
url: "<%=path%>" + "/queryEvaluateByuserId.do",
//返回是json数据
dataType: "json",
async:false,
data:{
},
success: function(data){
str = "";
if(data != null){
//循环表单列表
for (var i in data)
{
var num = parseInt(i) + 1 ;
str +="<tr><td>" + num + "</td><td>"
+ data[i]['name'] + "</td><td>"
+ data[i]['price'] + "元</td>"
+ "</tr>";
}
$(".trtd4").after(str);
}else{

}

},
error: function(data){
}
})
});
}
</script>

jsp部分:


<div class="tab-pane" id="B" style="text-align:center;">
<div class="row marg" >
<table border="2 " style="width:80%;text-align:center;">
<tr class="trtd4">
<th>序号</th>
<th>业主名</th>
<th>金额</th>
</tr>
</table>
</div>
</div>

在servlet中用到了阿里巴巴的快速转换json的包com.alibaba.fastjson.JSON:


private void queryEvaluateByuserId(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException, ServletException{
HttpSession session=request.getSession();
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
Cookie[] cookies = request.getCookies();
int ownerId = 0;
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
if (cookie.getName().equals("ownerId")) {
ownerId = Integer.parseInt(cookie.getValue());
}
}
List<Order> orderList = new ArrayList<>();
List<Evaluate> queryEvaluateList = new ArrayList<>();