为什么这里不需要JSONP ?

时间:2020-12-31 00:10:36

Im just trying to wrap my head round JSON/JSONP and cross domain issues.

我只是想把我的头绕到JSON/JSONP和跨域问题上。

Heres an example I found.

这是我发现的一个例子。

$(document).ready(function() {
  var user = "jamesbarnett"; //treehouse username

  /* get treehouse profile info via JSON */
  $.getJSON("https://teamtreehouse.com/" + user + ".json", function(data) { 
    console.log(data);// intialize list
    $("#badges").html('<ol>');
    var output = "";
    /* loop through the JSON, parse out badge name & icon
    wrap it in some HTML. */    
    for (var i in data.badges) {
        output += "<li>";
        output +="<figure>";
        output +="<figcaption>" + data.badges[i].name + "</figcaption>";
        output += "<img src = '" + data.badges[i].icon_url + "'/>";
        output+="</figure>";
        output += "</li>";    
    }
    $("#badges ol").append(output); // append li
    $("#badges ol").append('</ol>'); // close list

    /* hide spinner and then output HTML we built in the for loop */
    $(".spinner").hide();
  });
});

https://codepen.io/jamesbarnett/pen/oHsvr

https://codepen.io/jamesbarnett/pen/oHsvr

Can someone please explain why, in this example there is no cross domain issues (and the person has not needed to use JSONP)

有人能解释一下为什么在这个例子中没有跨域问题(而且这个人不需要使用JSONP)

Since the data comes from Treehouse domain...and is being displayed on codepen.io.... is this not a cross-domain?

由于数据来自树屋域……和被显示在codepen.io ....这不是一个交叉域吗?

1 个解决方案

#1


1  

Here is a response of curl -v https://teamtreehouse.com/jamesbarnett.json:

以下是curl -v https://teamtreehouse.com/jamesbarnett.json的响应:

< HTTP/1.1 200 OK
... Response truncated for brevity ...
< X-Content-Type-Options: nosniff
< Access-Control-Allow-Origin: *
< Access-Control-Allow-Methods: GET, OPTIONS
< Access-Control-Max-Age: 1728000
< ETag: W/"497006ef8221ce12b09998c0cdee8153"
< Cache-Control: max-age=0, private, must-revalidate
... Response truncated for brevity ...

Notice Access-Control-Allow-Origin: *. This means that they allow any domain to send XHR request. Hence, no CORS error.

注意Access-Control-Allow-Origin:*。这意味着它们允许任何域发送XHR请求。因此,没有歌珥错误。

#1


1  

Here is a response of curl -v https://teamtreehouse.com/jamesbarnett.json:

以下是curl -v https://teamtreehouse.com/jamesbarnett.json的响应:

< HTTP/1.1 200 OK
... Response truncated for brevity ...
< X-Content-Type-Options: nosniff
< Access-Control-Allow-Origin: *
< Access-Control-Allow-Methods: GET, OPTIONS
< Access-Control-Max-Age: 1728000
< ETag: W/"497006ef8221ce12b09998c0cdee8153"
< Cache-Control: max-age=0, private, must-revalidate
... Response truncated for brevity ...

Notice Access-Control-Allow-Origin: *. This means that they allow any domain to send XHR request. Hence, no CORS error.

注意Access-Control-Allow-Origin:*。这意味着它们允许任何域发送XHR请求。因此,没有歌珥错误。