<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript - read JSON from URL</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
<script>
function setup() {
loadJSON("https://www.westelm.com/services/catalog/v4/category/shop/new/all-new/index.json", gotData, 'jsonp');
}
function gotData(data){
alert(data);
}
</script>
</body>
</html>
我是开发者角色的新手,请帮忙。首先,它一直给我拒绝访问网址ERROR!然后我了解了jsonp并添加了它。现在我没有看到任何显示,当我应该得到json数据。 !来自url的JSON数据是正确的,在JSONLINT中运行它!
答案 0 :(得分:0)
var xmlhttp = new XMLHttpRequest();
var url = "https://www.westelm.com/services/catalog/v4/category/shop/new/all-new/index.json";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
console.log(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
该代码通常可以正常工作,但为此您应该收到此错误:
Failed to load
https://www.westelm.com/services/catalog/v4/category/shop/new/all-
new/index.json: No 'Access-Control-Allow-Origin' header is present on
the requested resource. Origin 'null' is therefore not allowed access.
The response had HTTP status code 403.
这是因为此服务器不允许JSON Reqs,并且不允许您访问。您可以尝试使用CORS(https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS),但我不确定对您有多大帮助