简体   繁体   中英

how to grab JSON Data from url using JavaScript? (new to JSON)

<!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>

I am new to the developer role, please help. First it kept giving me Access denial to the url ERROR!. Then i learned about jsonp and added it. Now i don't see anything showing up, when i should be getting the json data. !JSON data from the url is correct ran it in JSONLINT!

 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(); 

That code will normally work, but for this you should be getting this error:

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.

That's because this server doesn't allow JSON Reqs, and will not allow you access. You could try using CORS ( https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS ) but I'm not sure how much that will help you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM