在我的代码中查找解析JSON的错误

Finding the error in my code for parsing JSON

本文关键字:JSON 错误 查找 我的 代码      更新时间:2023-09-26

我搜索了几个小时,检查了文档,但我似乎找不到我的jQuery出了什么问题…我正在尝试练习阅读本地JSON文件并在HTML的主体中显示内容。

$(document).ready(function(){
    $.getJSON( "test.json", function( data ) {
        var items = [];
        $.each( data, function( key, val ) {
            items.push( "<li id='" + key + "'>" + val + "</li>" );
            console.log(data); 
        });
        $( "<ul/>", {
            "class": "my-new-list",
            html: items.join( "" )
        }).appendTo( "body" );
    });
});
下面是同一文件夹中实际的json文件:
{
  "one": "Singular sensation",
  "two": "Beady little eyes",
  "three": "Little birds pitch by my doorstep"
}

我只得到一个空白体当我打开index.html。index.html有

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script type="text/JavaScript" src="script.js"></script>  

所以我知道链接应该不会有问题....

更新:下面是控制台的新输出:

 XMLHttpRequest cannot load file:///C:/Users/Steven/Desktop/meltApplication/test.json.    Received an invalid response. Origin 'null' is therefore not allowed access. 

//:表示使用与当前页面相同的模式,因此,如果您在本地打开文件(如果地址栏中的URL是file://…),您的模式是file://,因此脚本将在您的本地机器上查找JQuery,如错误提示。

执行@Melvinr所说的正确加载JQuery,然后您可以继续调试剩余的代码

您没有添加http协议,因此这意味着浏览器将尝试在本地查找js

添加jquery引用

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>