Ajax实现收藏论坛版块功能,并异步返回提示信息
一、描述
在论坛的版块页面上有一个收藏本版的超链接,点击该超链接即可收藏该版块,但是为了防止重复收藏,以及未登录就收藏的错误操作,我们采用Ajax异步返回收藏提示信息。
二、实现细节
1、在jsp页面中点击收藏超链接,执行其onclick事件中的方法,而不是跳转到某个新的页面。
2、在boardCollect.js文件中采用Ajax技术,执行后台的收藏版块的操作,并且异步写回提示信息。
3、根据返回的提示信息,显示页面中的相应提示信息控件。
三、源代码
1、boardCollect.js
// 创建请求 var http_request; function createXMLHttpRequest(){ http_request=false; if(window.XMLHttpRequest){ http_request=new XMLHttpRequest(); //初始化http_request if(http_request.overrideMimeType){ http_request.overrideMimeType("text/html"); } }else if(window.ActiveXObject){ try{ http_request=new ActiveXObject("Msxml2.XMLHTTP"); //在IE中创建XMLHttpRequest对象,新版IE }catch(e){ try{ http_request=new ActiveXObject("Microsoft.XMLHTTP"); //在IE中创建XMLHttpRequest对象旧版IE }catch(e){} } } if(!http_request){ window.alert("不能创建XMLHttpRequest对象实例"); return false; } } function boardCollect(id){ showCollects("boardCollect.action?boardId="+id); } function showCollects(url){ //调用createXMLHttpRequest创建http_request createXMLHttpRequest(); //onreadystatechange状态发生变化,返回processRequest方法进行处理 http_request.onreadystatechange=processRequest; http_request.open("GET",url,true); http_request.send(null); } // 处理返回信息的函数 function processRequest(){ if(http_request.readyState==4){ if(http_request.status==200){ //正常返回,获取返回的responseText数据 var com = eval('('+http_request.responseText+')'); var feedback = com.feedback; if(feedback=="true"){ //收藏成功 document.getElementById("ntcwin").style.display="block"; function remove(){ document.getElementById("ntcwin").style.display="none"; } //显示1.5秒后消失 setInterval(remove,1500); }else if(feedback=="already collect"){ //已经收藏,不能重复收藏,将页面上提示重复收藏的div显示出来 document.getElementById("fwin_a_favorite").style.display="block"; }else{ //未登录就收藏,修改页面上errorInfo显示的提示的错误信息 document.getElementById("errorInfo").innerHTML="抱歉,您还未登录没有此权限,请登录后重试"; document.getElementById("fwin_a_favorite").style.display="block"; } } } } //隐藏tcl对应的div function hideWindow(tcl){ document.getElementById(tcl).style.display="none"; }
2、board.jsp(有些css代码没有上传,也许会出现显示格式问题)
<%@ page language="java" pageEncoding="UTF-8"%> <%@ taglib uri="/struts-tags" prefix="s"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head > <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>版块收藏</title> <style type="text/css"> .pbt { margin-bottom: 10px; } .ie6 .pbt .ftid a, .ie7 .pbt .ftid a { margin-top: 1px; } .cl:after { clear: both; content: "."; display: block; height: 0; visibility: hidden; } </style> <script type="text/javascript" src="boardCollect.js"></script> </head> <body> <div id="append_parent"> <!--fwin_a_favorite为信息已经收藏的提示信息,当该用户已经收藏了这个版块则提示 --> <div id="fwin_a_favorite" class="fwinmask" style="position: fixed; z-index: 201; left: 438.5px; top: 72.5px;display:none;" initialized="true"> <table class="fwin" cellspacing="0" cellpadding="0"> <tbody> <tr> <td class="m_l" )"="" ondblclick="hideWindow('fwin_a_favorite')" style="cursor:move"> </td> <td id="fwin_content_a_favorite" class="m_c" style="" fwin="a_favorite"> <h3 id="fctrl_a_favorite" class="flb" style="cursor: move;"> <em>提示信息</em> <span> <a class="flbc" title="关闭" onclick="hideWindow('fwin_a_favorite');" href="javascript:;">关闭</a> </span> </h3> <div class="c altw"> <div id="errorInfo" class="alert_error"> 抱歉,您已收藏,请勿重复收藏 </div> </div> <p class="o pns"> <button id="closebtn" class="pn pnc" onclick="hideWindow('fwin_a_favorite');" type="button" fwin="a_favorite"> <strong>确定</strong> </button> </p> </td> <td class="m_r" "="" ondblclick="hideWindow('a_favorite')" onmousedown="dragMenu($('fwin_a_favorite'), event, 1)" style="cursor:move"></td> </tr> </tbody> </table> </div> <!--"ntcwin"为第一次收藏该版块的提示 --> <div id="ntcwin" class="popuptext" style="position: fixed;left: 502.5px; top: 191px; display:none; " initialized="true"> <table class="popupcredit" cellspacing="0" cellpadding="0"> <tbody> <tr> <td class="pc_l"> </td> <td class="pc_c"> <div class="pc_inner"> <i>信息收藏成功 </i> </div> </td> <td class="pc_r"> </td> </tr> </tbody> </table> </div> </div> <!--"a_favorite"超链接提供用户收藏版块的功能,点击该链接就可以调用Ajax异步收藏版块并返回提示信息 --> <div class="pbt cl"> <a id="a_favorite" class="fa_fav" onclick="boardCollect(${rd.boardName.board_id});" href="javascript:void(0);"> 收藏本版 <strong id="number_favorite" class="xi1"> <c:if test="${rd.boardName.board_collectNum > 0}"> <span id="number_favorite_num">(${rd.boardName.board_collectNum})</span> </c:if> </strong> </a> </div> </body> </html>
3、后台处理收藏版块的java源代码
/** *收藏版块 */ public String boardCollect(){ System.out.println("enter boardCollect try boardId="+boardId); try { HttpServletResponse response; response=ServletActionContext.getResponse(); response.setContentType( "text/json;charset=utf-8"); response.setHeader( "Cache-Control", "no-cache"); response.setHeader( "Pargma", "no-cache"); PrintWriter out; out = response.getWriter(); //mcpForumPost = mcpForumPostDAO.findById(postId); JSONObject js = new JSONObject(); ScpnUser u=(ScpnUser)this.getSession().get("user"); if(u!=null){ //判断该用户是否已经收藏该版块 String exitBoardCollect = "SELECT COUNT(*) FROM mcp_forum_board_collect where user_id= "+u.getUserId()+" and board_id="+boardId; System.out.println("exitBoardCollect:"+exitBoardCollect); Integer count=jdbcTemplate.queryForInt(exitBoardCollect); if(count>0){ js.put("feedback", "already collect"); }else{ Timestamp currentTime = new Timestamp(System.currentTimeMillis()); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time = sdf.format(currentTime); //将收藏记录插入版块收藏表 String insertBoardCollect = "INSERT INTO mcp_forum_board_collect(board_id,user_id,board_collect_time) VALUES ("+boardId+","+u.getUserId()+",'"+time+"')"; System.out.println("insertPostCollect:"+insertBoardCollect); jdbcTemplate.update(insertBoardCollect); //更新版块收藏数量 String updateColNum = "UPDATE mcp_forum_board SET board_collectNum=1 where board_id="+boardId; System.out.println("updateColNum:"+updateColNum); jdbcTemplate.update(updateColNum); userLogger.insert(UserLogger.UPDATE, u.getAccount()+"收藏版块"); js.put("feedback", "true"); } }else { js.put("feedback", "not login"); } out.write(js.toString()); out.close(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return null; }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。