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" )"="" οndblclick="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="关闭" οnclick="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" οnclick="hideWindow('fwin_a_favorite');" type="button" fwin="a_favorite">
				<strong>确定</strong>
				</button>				
				</p>
				</td>
				<td class="m_r" "="" οndblclick="hideWindow('a_favorite')" οnmοusedοwn="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" οnclick="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;
	}
	





  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
实现异步登录功能,可以使用 AJAX 技术来实现。下面是基本的实现步骤: 1. 编写前端页面,包含登录表单和提交按钮。 2. 编写 JavaScript 代码,监听提交按钮的点击事件,获取表单数据,并通过 AJAX 技术将数据发送到后端。 3. 后端接收到数据后,进行登录验证。如果验证成功,返回登录成功信息;否则返回失败信息。 4. 前端通过 AJAX 接收到后端返回的信息,并进行处理。如果登录成功,跳转到主页;否则给出提示信息,让用户重新输入。 下面是一个简单的示例代码: HTML 代码: ``` <form id="loginForm"> <label>用户名:</label> <input type="text" name="username"><br> <label>密码:</label> <input type="password" name="password"><br> <button type="submit">登录</button> </form> ``` JavaScript 代码: ``` $(function() { // 监听提交按钮的点击事件 $('#loginForm').submit(function(event) { // 阻止表单的默认提交行为 event.preventDefault(); // 获取表单数据 var formData = $(this).serialize(); // 发送 AJAX 请求 $.ajax({ url: 'login.php', type: 'post', data: formData, dataType: 'json', success: function(response) { // 处理后端返回的数据 if (response.success) { // 登录成功,跳转到主页 window.location.href = 'index.html'; } else { // 登录失败,给出提示信息 alert(response.message); } } }); }); }); ``` PHP 代码: ``` // 接收表单数据 $username = $_POST['username']; $password = $_POST['password']; // 进行登录验证 if ($username == 'admin' && $password == '123456') { // 登录成功,返回成功信息 echo json_encode(array('success' => true)); } else { // 登录失败,返回失败信息 echo json_encode(array('success' => false, 'message' => '用户名或密码错误')); } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值