I am trying to consume the data source from a proxy service, and the data source has the following structure:
{
"Items": {
"ItemSection": [
{
"Food": {
"Name": "Potato Chips",
"itemID": "24501"
},
"category": "Snack",
"description": "Some description",
"available": "Shop A"
},
{
"Food": {
"Name": "Cookie",
"itemID": "24510"
},
"category": "Snack",
"description": "Some description in here.",
"available": [
"Shop A",
"Shop B"
]
},
Below is the response headers :
Status Code: 200 OK
Access-Control-Request-Method: OPTIONS, GET
Cache-Control: public, max-age=321
Content-Length: 42158
Content-Type: application/json
Date: Thu, 29 Sep 2016 20:45:49 GMT
Expires: Thu, 29 Sep 2016 20:51:11 GMT
Last-Modified: Thu, 29 Sep 2016 20:31:11 GMT
Server: Microsoft-IIS/8.5
Vary: *
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
access-control-allow-credentials: true
access-control-allow-headers: Authorization, Content-Type
access-control-allow-origin
and this is how I consume the data source with JavaScript:
function getItems() {
var uri = "proxy url goes here";
var xhr = new XMLHttpRequest();
xhr.open("GET", uri, true);
xhr.onload = function () {
var resp = JSON.parse(xhr.responseText);
showItems(resp.value);
}
xhr.send(null);
}
function showItems(item) {
var tableContent = "<tr class='ItemTitle'><td>Item Lists</td></tr>\n";
for (var i = 0; i < item.length; ++i) {
var record = item[i];
tableContent += "<tr><td>" + record.Name + "</td></tr>\n";
}
document.getElementById("showItem").innerHTML = tableContent;
}
The data source doesn't show up as I run the page, all I got is a blank page with the title Items
displayed only. But if I replace the code inside xhr.onload = function() {}
to this:
var version_d = document.getElementById("ItemLists");
version_d.innerHTML = xhr.responseText;
Then all data source will be displayed on the page but it just displaying a raw data source and I cannot select what I want to show on the page by using showItems
function.
Here's my html page :
<!DOCTYPE html>
<html>
<head>
<title>List</title>
<link rel="stylesheet" type="text/css" href="ShowOrders.css" />
<script src="ShowOrders.js"></script>
<script>
window.onload = getItems;
</script>
</head>
<body>
<h1>Items</h1>
<table id="showItem"></table>
</body>
</html>
Why it is not working with JSON.parse
? am I using the Cross-origin resource sharing (CORS) method wrong ? How can I get it works with out using any external libraries or frameworks (pure JavaScript only) ?