-->

Can headers be sent in an AJAX request?

2020-07-22 19:31发布

问题:

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).

回答1:

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.



回答2:

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.



回答3:

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