如何使用AJAX请求设置Cookie值? [英] How to set cookie value with AJAX request?

查看:988
本文介绍了如何使用AJAX请求设置Cookie值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为AJAX请求设置Cookie值,但下面的代码不起作用。

I want to set a cookie value on an AJAX request but the code below doesn't work.

$.ajax({
    type: "GET",    
    url: "http://example.com",
    cache: false,
    setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl",
    crossDomain: true,
    dataType: 'json',
    success: function (data) {
        alert(data);
    });

如何在标题中设置Cookie?

How can I set cookies in the header?

推荐答案

基本上,ajax请求以及同步请求会自动发送您的文档Cookie。所以,你需要设置你的cookie为文档,而不是请求。但是,您的请求是跨域的,事情变得更复杂。基于此答案,除了设置文档Cookie,您应允许其发送到跨域环境:

Basically, ajax request as well as synchronous request sends your document cookies automatically. So, you need to set your cookie to document, not to request. However, your request is cross-domain, and things became more complicated. Basing on this answer, additionally to set document cookie, you should allow its sending to cross-domain environment:

type: "GET",    
url: "http://example.com",
cache: false,
// NO setCookies option available, set cookie to document
//setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl",
crossDomain: true,
dataType: 'json',
xhrFields: {
    withCredentials: true
},
success: function (data) {
    alert(data);
});

这篇关于如何使用AJAX请求设置Cookie值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆