在浏览器上设置cookies,都是通过DOM的document.cookie实现,少了这个接口是无法将cookie保存在浏览器上的。浏览器端的Ajax请求时通过浏览器端的脚本(VBscript或Javascript)来实现,而DOM就是面向浏览器端脚本的接口。Ajax和cookies的设置和读取没有冲突的。
例子:
Ajax("getCookies.php",callback);
function callback(data){
document.cookie=data;//将cookie设置到浏览器,这里写入到浏览器的cookie是由getCookies.php返回的内容。
}
function Ajax(){
//Author: 扎俊
//Email:men_779@126.com
//Question: http://hi.baidu.com/men779
this.url=arguments[0]||"";
this.callback=arguments[1]||callAjaxBack;
this.method=arguments[2]||"GET";
var xThis=this;
function callAjaxBack(){}
var xmlHttp;
try{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e){
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e){
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
alert("Some Error Detected!");
return null;
}
}
}
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
xThis.callback(xmlHttp.responseText);
}
}
xmlHttp.open(this.method.toUpperCase(),this.url,false);
xmlHttp.send(null);
}
能。跟servlet的写法是一样的、
ajax把要保存的传给后台,后台设置cookie就可以了