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

查看:100
本文介绍了如何使用 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天全站免登陆