ajax+cookie實現網易新聞頂一下效果。
<a href='網頁特效:get_top_num(1);'>頂一下</a>
ajax
function getCookie(c_name){ //檢測cookie
if (document.cookie.length>0){
c_start=document.cookie.indexOf(c_name + "=")
if(c_start!=-1){
c_start=c_start + c_name.length+1;
c_end=document.cookie.indexOf(";",c_start);
if(c_end==-1) c_end=document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}
}
return "";
}
function setCookie(c_name,value,expiredays){ //設定cookie
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}
function createXMLHttpRequest(){ //建立XMLHttpRequest對象
if(window.ActiveXObject){ //IE
try {
return new ActiveXObject("Microsoft.XMLHTTP");
} catch(e){
return;
}
}else if(window.XMLHttpRequest){ //Mozilla,firefox
try {
return new XMLHttpRequest();
} catch(e){
return;
}
}
}
function get_top_num(id){ //主調函數
var get_top_cookie=getCookie('get_top_'+id+'_cookie');
if(get_top_cookie!=null && get_top_cookie!=""){
alert('此條評論你已經支援過了');
}
else{
var xmlHttp=createXMLHttpRequest();
var url = "action.php教程?action=top_num&id="+id;
if (id==""){
return false ;
}
if (xmlHttp){
callback = getReadyStateHandler(xmlHttp,id);
xmlHttp.onreadystatechange = callback;
xmlHttp.open("GET", url,true);
xmlHttp.send(null);
}
setCookie('get_top_'+id+'_cookie','istop',1);
}
}
function getReadyStateHandler(xmlHttp,id){ //伺服器返回後處理函數
var top_num = document.getElementById("top_num_"+id).innerHTML;
return function (){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
if (xmlHttp.responseText==1){
document.getElementById("top_num_"+id).innerHTML=Number(top_num)+1;
}
}
}
}
}
action.php檔案
是php mysql教程操作,由於簡單這裡主不作放代碼了。