<script type="text/javascript" src="js/jquery-1.9.1.js"></script>
<script>
$(function(){
$.ajax({
url:'http://www.xxx.com/users/syncLogin',
type:"GET",
dataType:"jsonp",
jsonp:'callback',
success:function(data){
document.cookie="ECS_ID="+data.id;
alert(data.id);
}
});
});
</script>
public function syncLogin(){
$this->autoRender = false;
$callback=$_GET['callback'];
echo $callback.'('.json_encode(array('id'=>$_COOKIE[ECS_ID])).')';
}
第二版:第一版cookie改变后需要刷新才生效
$.ajax({
url:'http://www.xxx.com/users/syncLogin',
type:"GET",
dataType:"jsonp",
jsonp:'callback',
success:function(data){
var cookie_str=document.cookie;
var date=new Date();
date.setTime(date.getTime()+365*24*3600*1000);
document.cookie="ECS_ID="+data.id+";expires="+date.toGMTString();
cookie_str=cookie_str.replace(/; /g,';');
var cookie_array=cookie_str.split(';');
for(var i=0,len=cookie_array.length;i<len;i++){
if(cookie_array[i].split('=')[0]=='ECS_ID'){
if(cookie_array[i].split('=')[1]!=data.id+''){
location.reload(1);
}
}
}
}
});
第三版:提取function
function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}
function getCookie(c_name)
{
var cookie=document.cookie;
var cookie_len=document.cookie.length;
if (cookie_len>0){
c_start=cookie.indexOf(c_name + "=")
if (c_start!=-1){
c_start=c_start + c_name.length+1;
c_end=cookie.indexOf(";",c_start);
if (c_end==-1){
c_end=cookie_len;
}
return unescape(cookie.substring(c_start,c_end));
}
}
return "";
}
$.ajax({
url:'http://www.xxx.com/users/syncLogin',
type:"GET",
dataType:"jsonp",
jsonp:'callback',
success:function(data){
var cookie_str=document.cookie;
var cookie_ecs_id=getCookie('ECS_ID');
setCookie('ECS_ID',data.id,365);
if(cookie_ecs_id!=data.id+''){
location.reload(1);
}
}
});