【问题标题】:How read cookies by jsonp?jsonp如何读取cookies?
【发布时间】:2016-09-09 17:52:06
【问题描述】:

您好,我有这段代码可以从 index.html 加载页面:

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.2.min.js"></script>
<script>
function jsonCallback(json){
  console.log(json);
  alert(document.cookie.json)
}

$.ajax({
  url: "https://run.plnkr.co/plunks/v8xyYN64V4nqCshgjKms/data-2.json",
  dataType: "jsonp"
});
</script>

我想要获取 cookie,所以在 https://run.plnkr.co/plunks/v8xyYN64V4nqCshgjKms/data-2.json 我已经在控制台中执行:document.cookie='test=123' 并返回未定义。为什么?我该如何解决?

这是该 URL 返回的内容:

jsonCallback(
  {
    "sites":
    [
      {
        "siteName": "SitePoint",
        "domainName": "https://www.sitepoint.com",
        "description": "SitePoint is a hub for web developers to share their passion for building incredible Internet things."
      },
      {
        "siteName": "A List Apart",
        "domainName": "http://alistapart.com/",
        "description": "A List Apart explores the design, development, and meaning of web content, with a special focus on web standards and best practices."
      },
      {
        "siteName": "Smashing Magazine",
        "domainName": "https://www.smashingmagazine.com/",
        "description": "Smashing Magazine delivers useful and innovative information to Web designers and developers."
      }
    ]
  }
);

【问题讨论】:

  • JSONP != JSON 您的示例的两端实际上都符合 JSONP,但 URL 上的 .json 给人的印象是它将返回 JSON。
  • alert(document.cookie.json)???

标签: javascript jquery json jsonp


【解决方案1】:

您不能在页面中使用 JavaScript 代码来读取其他来源的 cookie。如果您有http://example.com/foo.html,并且在其中从http://api.com/ 加载脚本(这是您使用JSONP 执行的操作),则与http://api.com/ 的响应一起返回的任何cookie 都与http://api.com/ 相关联。您无法使用 http://example.com/foo.html 中的 JavaScript 代码阅读它们。

【讨论】:

  • 没有办法得到它?
  • @Snoopy:如果有,那将是浏览器中的重大、重大、重大安全漏洞。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-31
  • 2013-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-23
相关资源
最近更新 更多