无法在数据表中加载json文件

时间:2017-08-30 09:01:10

标签: javascript jquery json datatables

我有这个index.html文件,其中包含一个数据表,该数据表应该填充来自同一文件夹中json文件的数据。这是index.html文件:

<!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,数据,chrome,chrome-extension,https。

2 个答案:

答案 0 :(得分:2)

根据请求的路径,您尝试向本地C:/驱动器发出请求 - 浏览器安全性会阻止此操作被允许,原因非常充分。

要使代码正常工作,您需要在Web服务器上运行请求。您可以在本地计算机上轻松安装IISXAMPP

答案 1 :(得分:0)

  

<强> CORS   跨源资源共享(CORS)是一种允许请求网页上受限资源(例如字体)的机制   来自第一个资源的域外的另一个域   服务。[1]网页可以自由嵌入跨源图像,   样式表,脚本,iframe和视频。[2]某些“跨域”   但是,默认情况下禁止Ajax请求,特别是Ajax请求   同源安全政策。

为请求添加有效的URL,与服务器运行的位置相同。

相关问题