search
HomeBackend DevelopmentPHP Tutorialphp+mysql+ajax点赞和踩的功能

嫌麻烦的也可以:点击下载


HTML:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"><script src="common/js/jquery.js" type="text/javascript"></script><script language="JavaScript" type="text/javascript">jQuery(function($) {	//这两个是鼠标放上去的效果	$(".zhan").hover(function(){ 		$(this).children("b").toggle();	}); 	$(".cai").hover(function(){	 	$(this).children("b").toggle();	});  }); </script><script type="text/javascript"> <!--这两个点击事件可以改进的,因为事件问题,所以就弄了两个点击事件  $(document).ready(function(e) {	//点赞(给力)	$('.zhan').click(function(){	var zhan=$(this);	var left = parseInt($(this).offset().left)+10, top =  parseInt($(this).offset().top)-10, obj=$(this);	$(this).append('<div id="zhan"><b>+1<\/b></\div>');	$('#zhan').css({'position':'absolute','z-index':'1', 'color':'#C30','left':left+'px','top':top+'px'}).animate({top:top-10,left:left+10},'slow',function(){	$(this).fadeIn('fast').remove();	var Num = parseInt(obj.find('span').text());	Num++;	obj.find('span').text(Num);	});$.ajax({  	url:"ajax.php?action=zan",  	type:"post",  	data:"answer_id="+$(this).attr("alt"),  	success:function(datas){  		zhan.unbind('click');  		zhan.parent().parent().siblings().children().children().unbind('click');		zhan.parent().parent().siblings().children().children().attr("class","evaluate-inner");  		zhan.attr("class","evaluate-inner"); 	}  }); }); //踩(不给力) $('.cai').click(function(){	var cai=$(this);	var left = parseInt($(this).offset().left)+10, top =  parseInt($(this).offset().top)-10, obj=$(this);	$(this).append('<div id="cai"><b>-1<\/b></\div>');	$('#cai').css({'position':'absolute','z-index':'1', 'color':'#7DAAD5','left':left+'px','top':top+'px'}).animate({top:top-10,left:left+10},'slow',function(){	$(this).fadeIn('fast').remove();	var Num = parseInt(obj.find('span').text());	Num--;	obj.find('span').text(Num);	}); $.ajax({  	url:"ajax.php?action=cai",  	type:"post",  	data:"answer_id="+$(this).attr("alt"),  	success:function(datas){  		cai.unbind('click');  		cai.parent().parent().siblings().children().children().unbind('click');		cai.parent().parent().siblings().children().children().attr("class","evaluate-inner");  		cai.attr("class","evaluate-inner"); 	}  }); }); }); //--></script><!--给力开始--><span data-evaluate="0" id="evaluate-1908165795" class="evaluate" alog-action="qb-zan-btn"> <span class="evaluate-outer"><!-----判断对应的回答的id是否在自己创建的存储赞和踩数据的php文件,如果赞或者踩存在一个的话就不能再单击----><span class="evaluate-inner {OVOV:if $answer_datas.ans_id|in_array:$zan_list or $answer_datas.ans_id|in_array:$cai_list/}{OVOV:else/}zhan{OVOV:/if/}" alt="{OVOV:$answer_datas.ans_id/}"> <b style="display:none" class="evaluate-tip evaluate-num-fixed">给力</b> <b class="evaluate-num evaluate-num-fixed"><span>{OVOV:$answer_datas.goods/}</span></b> </span> </span> </span><!--不给力开始--><span data-evaluate="0" id="evaluate-bad-1908165795" class="evaluate evaluate-bad" alog-action="qb-evaluate-outer"> <span class="evaluate-outer"> <span class="evaluate-inner {OVOV:if $answer_datas.ans_id|in_array:$zan_list or $answer_datas.ans_id|in_array:$cai_list/}{OVOV:else/}cai{OVOV:/if/}" alt="{OVOV:$answer_datas.ans_id/}"> <b style="display: none;" class="evaluate-tip evaluate-num-fixed">不给力</b> <b class="evaluate-num evaluate-num-fixed" style="display: inline-block;"><span>{OVOV:$answer_datas.bads/}</span></b> </span> </span> </span><!--评论回答开始-->



HTML对应的php文件


<?php $action=$_GET['action'];//获取get方式传过来的actionrequire_once("array/ovovsys_zan.php");switch($action){	case 'detail':		/*****赞开始****/		$zan_list = json_decode(str_replace("'",'"',$zan_json),true);		$zan_lists=array();		foreach($zan_list as $key=>$value){			if($value['uid']==$uid){		 		$zan_lists[]=$value['answer_id'];			}		} 		$smarty->assign('zan_list',$zan_lists);//查询当前登录的会员的uid对应的点赞的回答 		/*****赞结束****/ 		/*****踩开始****/		$cai_list = json_decode(str_replace("'",'"',$cai_json),true);		$cai_lists=array();		foreach($cai_list as $key=>$value){			if($value['uid']==$uid){		 		$cai_lists[]=$value['answer_id'];			}		} 		$smarty->assign('cai_list',$cai_lists);//查询当前登录的会员的uid对应的踩的回答 		/*****踩结束****/		$smarty->display('自己的静态页面');		exit();	break;}?>


ajax文件:

<?php require_once("array/ovovsys_zan.php");//这里引用array文件夹中的数组文件$action=trim($_GET['action']);if(empty($action)){	echo '<font color=red>参数错误!';exit();}switch($action){	 case 'zan'://点赞(给力)		//$zan_json是数组文件中设置的数组变量,存的是json数据----1		$zan_array = json_decode(str_replace("'",'"',$zan_json),true);				//获取当前的会员的uid-----2		$user_answer['uid']=$uid;		//获取对应的赞的回答的id----2		$user_answer['answer_id']=$_POST['answer_id'];				//将会员的uid和答案的id一块的数组放到指定的数组中----3		$zan_array[]=$user_answer;				$config_path = 'shuzu/ovovsys_zan.php';		if(!file_exists($config_path)){			$Base->ErrorMsg('文件错误:shuzu/ovovsys_zan.php 不存在!');exit();		}				//将指定的数组转换成json数据,并且将双引号转换成单引号,不然放到数组文件中后会出错----4		$zan_new_json = str_replace('"',"'",json_encode($zan_array));				$fp = @fopen($config_path,'r+');		if(!$content = @fread($fp,filesize($config_path))){			$Base->ErrorMsg('无法读取shuzu/ovovsys_zan.php文件!');exit();		}				//执行替换,将数组文件中对应的json数据----5		$content = str_replace("\$zan_json = \"{$zan_json}\"","\$zan_json = \"{$zan_new_json}\"",$content);		$fp = @fopen($config_path,'w+'); 		@fwrite($fp,$content); 				//修改对应的数据表中的数据----5		$Db->ThisQuery("update `".$db_prefix."ask_answers` set `goods`=`goods`+1 where `ans_id`=".$user_answer['answer_id']."");		exit();	break;	 case 'cai'://踩(不给力)		$cai_array = json_decode(str_replace("'",'"',$cai_json),true);		$user_answer['uid']=$uid;		$user_answer['answer_id']=$_POST['answer_id'];		$cai_array[]=$user_answer;		$config_path = 'shuzu/ovovsys_zan.php';		if(!file_exists($config_path)){			$Base->ErrorMsg('文件错误:shuzu/ovovsys_zan.php 不存在!');exit();		}		$cai_new_json = str_replace('"',"'",json_encode($cai_array));		$fp = @fopen($config_path,'r+');		if(!$content = @fread($fp,filesize($config_path))){			$Base->ErrorMsg('无法读取shuzu/ovovsys_zan.php文件!');exit();		}		$content = str_replace("\$cai_json = \"{$cai_json}\"","\$cai_json = \"{$cai_new_json}\"",$content);		$fp = @fopen($config_path,'w+'); 		@fwrite($fp,$content); 		$Db->ThisQuery("update `".$db_prefix."ask_answers` set `bads`=`bads`-1 where `ans_id`=".$user_answer['answer_id']."");		exit();	break;}?>


对应的数据文件(因为创建数据库时没有创建踩和赞的再断,所以这里就用php文件存变量的方式保存了一下答案对应的赞和踩的数据,其中包含用户的id和答案的id)

<?php $zan_json = "";$cai_json = "";?>你没看错,就是两个变量

如果嫌复制着麻烦的话,也可以点击下载压缩文件,亲,不要积分的哟!



Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

PHP Logging: Best Practices for PHP Log AnalysisPHP Logging: Best Practices for PHP Log AnalysisMar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

Explain the concept of late static binding in PHP.Explain the concept of late static binding in PHP.Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Customizing/Extending Frameworks: How to add custom functionality.Customizing/Extending Frameworks: How to add custom functionality.Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

Framework Security Features: Protecting against vulnerabilities.Framework Security Features: Protecting against vulnerabilities.Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),