2016-09-29 23 views
0

我想消費從代理服務的數據源和數據源的結構如下:不能使用來自代理服務JSON數據源

{ 
    "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" 
     ] 
    }, 

下面是響應頭:

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 

,這是我如何消費用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; 
} 

的數據源不顯示爲我運行該頁面,我得到的只是一個空白頁面,僅顯示標題Items。但是,如果我更換裏面的代碼xhr.onload = function() {}這樣:

var version_d = document.getElementById("ItemLists"); 
version_d.innerHTML = xhr.responseText; 

然後,所有的數據源將顯示在頁面上,但它只是顯示一個原始數據來源,我不能選擇我想通過在頁面上顯示什麼showItems功能。

這裏是我的html頁面:

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

爲什麼它不與JSON.parse工作?我是否使用跨源資源共享(CORS)方法錯誤?我怎樣才能使用任何外部庫或框架(僅限純JavaScript)來使用它?

+0

那麼,什麼是錯誤?瀏覽器的控制檯中是否有一個? – epascarello

+0

你可以從'xhr.responseText'中獲取該字符串嗎? –

+0

@AskingQuestions是的我可以用'version_d.innerHTML = xhr.responseText;' – Phantom

回答

0

resp.value

JSON.parse直接returns.the解析對象,所以resp.value是未定義的。

你只是想

return resp;

相關問題