开发者

Prevent Cookies From Being Sent on AJAX Request

I have a web service that I invoke from script but that does not need any information stored in cookies. Anytime I make a request to the service, the cookie is sent along with it. I understand that by default cookies are sent with HTTP request, but is there any way at all to override that behavior and not send the cookie?

In a nutshell, I am issuing my request like this:

$.ajax({
    type: "POST",
    cache: false,
    url: url,
    data: data,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(response) { successFunc(response); },
    error: function(xhr)开发者_如何学JAVA { errorFunc(xhr); }
});


Send AJAX requests to cookie-less subdomain on your server. So you app is www.mydomain.com and ajax requests are served from api.mydomain.com which you never set a cookie on. Also a great idea to do this with static files like images etc...

see the "Use Cookie-free Domains for Components" section of http://developer.yahoo.com/performance/rules.html


Another approach would be prior to doing $.ajax:
1. get the cookies from the browser for your domain with javascript (save them in a global variable)
2. delete the cookies for your domain with javascript from the browser
3. do the $.ajax call
4. place the cookies (from the global variable) back in the browser.

If you don't need the cookies from your domain at all just delete them (so skip 1. and 4.).


The withCredentials flag is needed to actually send cookies with cross-origin ajax calls.

See: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials

Setting it to false will prevent cookies from being sent.

With same-origin requests you will need to follow the other answers mentioned here.


You are correct in saying that browsers send matching (path + domain + session) cookies along with the HTTP request. This is critical for the cookie mechanism to work.

Couldn't you simply, not read the cookies?

Additionally, when the cookie is originally set, you can set what directory (and its subdirectories) can access the cookie.

For example, if you set a cookie to be read in /foo/bar/ only, a file located in /whatever/ajaxHandler.php cannot see those those cookies.

Check this out: http://us.php.net/setcookie

While I'm not sure if you're using PHP, it could be a good starting point for you.


No, the cookie will always be sent.

You could how your cookies are sent to the browser, and use the http flag on them, which means they won't be sent via javascript.

Or (which lots of sites use), create a new subdomain which you never sent any cookies on.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜