2017-08-30 113 views
0

我有這個index.html文件,其中包含一個數據表,該數據表應該填充來自同一文件夾中的json文件的數據。這是index.html文件:無法在數據表中加載json文件

<!DOCTYPE html> 
<html> 
<head> 
<title>Display JSON File Data in Datatables | Example</title> 
</head> 
<body> 
<table id="empTable" class="display" width="100%" cellspacing="0"> 
    <thead> 
     <tr> 
      <th>Name</th> 
      <th>Designation</th> 
      <th>Office</th> 
      <th>Extension</th> 
      <th>Joining Date</th> 
      <th>Salary</th> 
     </tr> 
    </thead> 
    <tfoot> 
     <tr> 
      <th>Name</th> 
      <th>Designation</th> 
      <th>Office</th> 
      <th>Extension</th> 
      <th>Joining Date</th> 
      <th>Salary</th> 
     </tr> 
    </tfoot> 
</table> 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.13/datatables.min.css"/> 
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.13/datatables.min.js"></script> 

<script type="text/javascript"> 
$(document).ready(function() { 
    $('#empTable').dataTable({ 
     "ajax": "empdata.json", 
     "columns": [ 
      {"data": "name"}, 
      {"data": "designation"}, 
      {"data": "office"}, 
      {"data": "extension"}, 
      {"data": "joining_date"}, 
      {"data": "salary"} 
     ] 
    }); 
}); 
</script> 
</body> 
</html> 

的問題是JSON文件無法加載,我不知道如何解決它。這是在控制檯中的錯誤:

jquery.min.js:4的XMLHttpRequest無法加載的文件:/// C:/Users/user/Desktop/d/empdata.json _ = 1504083178306?。跨起源請求只支持協議方案:HTTP,數據,鍍鉻,鍍鉻的擴展,https.`

回答

2

鑑於請求的路徑,你正在試圖發出請求到本地驅動器C:/ - 由於很好的原因,瀏覽器安全性阻止了它被允許。

要使代碼正常工作,您需要在Web服務器上運行請求。您可以輕鬆安裝IISXAMPP在本地計算機上執行此操作。

0

CORS 跨域資源共享(CORS)是一種機制,允許在網頁上限制資源(如字體)被要求 從另一個域從第一資源 是外域提供服務。[1]一個網頁可以自由嵌入跨源圖像, 樣式表,腳本,iframe和視頻。[2]但是,某些「跨域」請求,特別是Ajax請求,在默認情況下被同源安全策略禁止爲 。

向請求添加一個有效的url,與服務器運行的地址相同。