ajax+cookie实现网易新闻顶一下效果。

作者:简简单单 2011-07-07

ajax+cookie实现网易新闻顶一下效果。
顶一下

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教程操作,由于简单这里主不作放代码了。

相关文章

精彩推荐