ajax发送post请求到controller

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>   
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>     
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="${pageContext.request.contextPath }/book/list" rel="external nofollow" >查询书单</a>
<table width="70%" border=1>
<tr>
  <td>书籍编号</td>
  <td>名称</td>
  <td>藏书量</td>
  <td>操作</td>
</tr>
<c:forEach items="${list}" var="book">
<tr>
  <td>${book.bookId }</td>
  <td>${book.name }</td>
  <td id=${book.bookId }>${book.number }</td>
  <td><input type="buttom" value="订阅" onclick="requestByJson(${book.bookId })"></td>
 
</tr>
</c:forEach>
</body> 
<script src="${pageContext.request.contextPath }/resources/js/jquery-3.2.1.js" type="text/javascript"></script>
<script type="text/javascript">

	function requestByJson(bid) {
		//alert(bid);
		var stid=12345678915;
		var p = {'studentId':stid};
		$.ajax({
			type : 'post',
			url : "${pageContext.request.contextPath }/book/"+bid+"/appoint",
			//设置contentType类型为json
			//contentType : 'application/json;charset=utf-8',//错误写法
			contentType : 'application/x-www-form-urlencoded; charset=UTF-8',//缺省值
			//json数据
			data: {'bookId':1004,'studentId':stid},//必传参数必须填写,位置任意。增加参数,不影响执行
			dataType: "json", //告诉服务器期待返回何种类型的数据
			//请求成功后的回调函数
			success : function(data) {
				//alert(JSON.stringify(data));
				var res = JSON.stringify(data);
				var res2 = eval("("+res+")");//转换成json对象
				alert(res2.data["stateInfo"]);//提示预约结果
				if(res2.data["state"]==1){//预约成功需要更新库存数
					var book = JSON.stringify(res2.data["appointment"]);
					var appointment = eval("("+book+")");
					$('td[id='+bid+']').html(appointment.book["number"]);
				}
			}
		});
	}
	

</script>
</html>

 请求成功后,对库存量进行更新显示。

使用到,jQuery选择器,JSON格式数据在js中如何由string成json对象。json对象可以在js中通过

1).号来得到某个属性的值。2)a[数字] 可以用索引方式获取某个属性的值 3)a[属性名] 可以通过属性名得到对应值。

猜你喜欢

转载自yhzhangdota.iteye.com/blog/2383011