如何通过jsonp读取cookie?

时间:2016-09-09 17:52:07

标签: javascript jquery json jsonp

您好我有这个代码从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'并返回undefined。为什么?我该如何解决?

以下是该网址返回的内容:

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."
      }
    ]
  }
);

1 个答案:

答案 0 :(得分:1)

您无法在页面中使用JavaScript代码来读取其他来源的Cookie。如果您有http://example.com/foo.html并且在其中加载了http://api.com/脚本(这是您正在使用JSONP进行的操作),那么随http://api.com/的响应返回的任何Cookie都与{{{ 1}}。您无法使用http://api.com/中的JavaScript代码阅读它们。