太原 2019-6-24 工作经历
文章总结
在jquery中
div元素被点击时,使用 $(this)
获取当前div的id 使用 $(this).attr(“id”);
获取当前div的name 使用 $(this).attr(“name”);
获取当前div便签对中的值 使用 $(this).text();
在Freemark中 Js的变量与jquery结合使用的话
#要加引号 用 +号与变量连接
$("#"+memberId).removeClass(‘collected’).addClass(‘collectio’).html(‘已收藏’);
//2020-5-23更新
批量获取select多选框
var dateValue= $(“select[name=‘interest’]”).get(i).value
项目中用的时 Freemark渲染
Html中
<div class="collected" id="${bookMember.id}">收藏</div>
JS中
$(function(){
//添加收藏
$(".collected").click(function(){
var value = $(this).text();
var memberId = $(this).attr("id");
if(value == "收藏"){
$.ajax({
type : "get",
dataType : "json",
url : "${base}/collect/inCollect",
contentType:"application/x-www-form-urlencoded",
data:
{"memberId":memberId },
success:function (data) {
if(data.code == 1){
$("#"+memberId).removeClass('collected').addClass('collectio').html('已收藏');
}else{
layer.msg(data.msg, {icon: 2, time: 800});
}
},//响应成功后的回调函数
});
}else{
$.ajax({
type : "get",
dataType : "json",
url : "${base}/collect/outCollect",
contentType:"application/x-www-form-urlencoded",
data:
{"memberId":memberId },
success:function (data) {
if(data.code == 1){
$("#"+memberId).removeClass('collectio').addClass('collected').html('收藏');
}else{
layer.msg(data.msg, {icon: 2, time: 800});
}
},//响应成功后的回调函数
});
}
});
});
后台
@Controller
@RequestMapping("/collect")
public class BookCollectController {
@RequestMapping("/inCollect")
public void inCollect(
Model model,
@RequestParam(required = false, value = "memberId", defaultValue = "") String memberId,
HttpServletRequest request, HttpServletResponse response) throws IOException {
Map<String,Object> result = Maps.newHashMap(); //定义一个HashMap集合 存储数据 返回前台
/---查询数据库的验证跳过----/
result.put("code", 1);
result.put("msg", "收藏成功");
printJSON(getStringOfObj(result), response);
}
//封装的方法。
protected void printJSON(Object o, HttpServletResponse response) {
PrintWriter out=null;
try {
response.setContentType("application/json;charset=UTF-8");
out = response.getWriter();
out.print(o);
out.flush();
} catch (IOException ex) {
logger.error(ex.getMessage());
}catch (Exception ex) {
logger.error(ex.getMessage());
}finally{
if(out!=null)
out.close();
}
}
}