开发者

Can headers be sent in an AJAX request?

Can I call the server to set a new cookie with an AJAX request (that is, after the page has already loaded)?

For example, when a visitor hits a link, ajax would open a php file that sets a new cookie like this:

setcookie('cookiename', 'true', time()+3000, "/",'...');

But this is done after the html (the page containing the actual <a> tag pressed) was rendered. Is it nevertheless ok to set cookies in ajax? (maybe because the php 开发者_开发百科file loaded is separate from the original html page).


You can have the server's response set a cookie, certainly. Remember that cookies are an HTTP thing, not an HTML thing; the fact that your original HTML file is already on the browser is irrelevant. Your ajax request is a separate HTTP request to the server, which (hopefully!) generates an HTTP response back to the browser; and that response can include a new Set-Cookie header.

I'm not a PHP person, you'll need to check that there are limitations in the PHP mechanism you're using for setting the cookie (I can't imagine there are). But fundamentally, no, there's no problem doing this. I've done it with both JSPs and classic ASP.


I've set cookies in the response to AJAX requests on my site and I haven't had any problems with it yet. (Although I haven't looked for problems.) It could be that some browsers don't set cookies when receiving them in an XmlHttpRequest but so far I've seen it work in IE, Chrome and Firefox.


Why not use javascript to edit cookies? Return the content of the cookie in JSON format and use javascript to store the values.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜