我只是试图围绕JSON / JSONP和跨域问题。
这是我发现的一个例子。
$(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
有人可以解释为什么,在这个例子中有没有跨域问题(并且该人不需要使用JSONP)
由于数据来自Treehouse域...并且正在codepen.io上显示....这不是跨域吗?
答案 0 :(得分:1)
以下是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 ...
注意Access-Control-Allow-Origin: *
。这意味着它们允许任何域发送XHR请求。因此,没有CORS错误。