我正在开发 Spotify 应用程序,并且还尝试使用 JQuery 的 $.ajax 函数登录 Reddit。登录有效,我可以在开发工具中看到响应 cookie,但是当我尝试访问 Reddit API 的任何需要通过调用发送登录 cookie 的部分时,它会失败,并且看起来 cookie 从未被发送。另外,查看开发工具的“Cookies”部分显示该网站(应用程序)没有 Cookie。
这是登录调用:
$.ajax({
type: 'POST',
url: 'http://www.reddit.com/api/login',
data: {
'user': $user,
'passwd': $password
},
success: function() {
alert("logged in!");
}
});
这是投票电话(从我可以在开发工具中看到的 cookie 复制的 userhash):
$.ajax({
type: 'POST',
url: 'http://www.reddit.com/api/vote',
data: {
'id': $id,
'dir': 1,
'uh': $userhash
},
success: function(data) {
console.log(data);
}
});
最佳答案
使用 jQuery 1.5.1 中添加的 xhrFields 属性可能会有所帮助:
登录电话:
$.ajax({
type: 'POST',
url: 'http://www.reddit.com/api/login',
data: {
'user': $user,
'passwd': $password
},
xhrFields: {
withCredentials: true
},
success: function() {
alert("logged in!");
}
});
投票电话:
$.ajax({
type: 'POST',
url: 'http://www.reddit.com/api/vote',
data: {
'id': $id,
'dir': 1,
'uh': $userhash
},
xhrFields: {
withCredentials: true
},
success: function(data) {
console.log(data);
}
});
这将告诉它将 XMLHTTPRequest 对象的 withCredentials 属性设置为 true,这是使用跨域 AJAX 调用时传递 cookie 所必需的。
关于javascript - Spotify (Javascript) 中的 ajax 调用后未保存 Cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11935908/